6

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);
Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124
COPILOT User
  • 301
  • 1
  • 3
  • 4

2 Answers2

14

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
  • 23,220
  • 2
  • 52
  • 66
2

the ?? operator.

string a = nullstring ?? "empty!";
Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
Darren Kopp
  • 76,581
  • 9
  • 79
  • 93