Nate Pet
Nate Pet

Reputation: 46222

c# null string?

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?

Upvotes: 0

Views: 269

Answers (4)

Chris Shain
Chris Shain

Reputation: 51329

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

Upvotes: 12

Tergiver
Tergiver

Reputation: 14517

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.

Upvotes: -1

hazzik
hazzik

Reputation: 13344

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

Upvotes: 2

L.B
L.B

Reputation: 116118

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

Upvotes: 6

Related Questions