The string does not concatenate as I would expect

I just do not understand why the following statement does not evaluate as I expected.

With UserFirstNameset to "Joe" and the UserLastNamevalue "Plumber", SpeakerNameonly "Joe" gets.

spr.SpeakerName = presenterRec.UserFirstName ?? "" + " " + 
    presenterRec.UserLastName ?? "";

Thoughts?

+3
source share
2 answers

Because, if presenterRec.UserFirstNameit is not null, you get that value, and the evaluation of your expression stops there.

In other words, you have a problem with the order of operations. Try the following:

spr.SpeakerName = (presenterRec.UserFirstName ?? "") 
                  + " " +  
                  (presenterRec.UserLastName ?? "");

Operator?? link

+14
source

A zero-coalescing operator has a rather low priority, as described in MSDN .

The solution, as already mentioned, adds parentheses

(presenterRec.UserFirstName ?? "") 
            + " " + 
            (presenterRec.UserLastName ?? "")

.NET ,

presenterRec.UserFirstName + " " + presenterRec.UserLastName

.

+5

All Articles