tags:

views:

405

answers:

2

Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?

//pseudo-codeish
string s = Coalesce(string1, string2, string3);

or, more generally,

object obj = Coalesce(obj1, obj2, obj3, ...objx);
+1  A: 

the ?? operator.

string a = nullstring ?? "empty!";

Darren Kopp
+11  A: 

As Darren Kopp said.

Your statement

object obj = Coalesce(obj1, obj2, obj3, ...objx);

Can be written like this:

object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;

to put it in other words:

var a = b ?? c;

is equivalent to

var a = b != null ? b : c;
Erik van Brakel