문제

I had the following:

string Name = name.First + " "  +  name.Last;

This returns Tom Jones just fine.

In case name.First may be null or name.Last may be null, I have the following:

string SpeakerName = name.First ?? string.Empty + " "  +  name.Last ?? string.Empty;

What is strange is that it only returns Tom. Why is this and how can I fix it such that if null it defaults to empty string for either first or last name?

도움이 되었습니까?

해결책

Because of the relative precedence of the ?? and + operators. Try this:

string SpeakerName = (name.First ?? "") + " " + (name.Last ?? "");

Your original example is evaluating as if it was:

string SpeakerName = name.First ?? ("" + " "  +  (name.Last ?? ""));

Also, read Jon's answer here: What is the operator precedence of C# null-coalescing (??) operator?

As he suggests there, this should work as well:

string SpeakerName = name.First + " " + name.Last;

Because that compiles to @L.B.'s answer below, minus the trim:

string SpeakerName = String.Format("{0} {1}", name.First, name.Last)

EDIT:

You also asked that first and last both == null makes the result an empty string. Generally, this is solved by calling .Trim() on the result, but that isn't exactly equivalent. For instance, you may for some reason want leading or trailing spaces if the names are not null, e.g. " Fred" + "Astair " => " Fred Astair ". We all assumed that you would want to trim these out. If you don't, then I'd suggest using a conditional:

string SpeakerName = name.First + " " + name.Last;
SpeakerName = SpeakerName == " " ? String.Empty : SpeakerName;

If you never want the leading or trailing spaces, just add a .Trim() as @L.B. did

다른 팁

string SpeakerName = String.Format("{0} {1}", name.First, name.Last).Trim();
string SpeakerName = name.First != null && name.Last != null 
                     ? string.Format("{0} {1}", name.First, name.Last) 
                     : string.Empty;
string fullName = (name.First + " "  +  name.Last).Trim();

This works for either or both being null and will not return a string with leading, trailing, or only spaces.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top