0

I will appreciate a logical explanation to this line of code. What will it achieve?

x = y ?? "";

where x is of type object and y is string variable.

Please note that the program compiled.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • 1
    Have you read the [documentation](https://msdn.microsoft.com/en-us/library/ms173224.aspx)? What haven't you understood? _" It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand"_ – Tim Schmelter Feb 18 '15 at 11:11
  • You should search or try something before asking here. Here is detailed documentation by msdn. https://msdn.microsoft.com/en-us/library/ms173224.aspx – Jenish Rabadiya Feb 18 '15 at 11:12
  • 2
    This is no ternary operator, and I'm not sure why you'd think so. `?:`, as in `x?y:z`, is often called a ternary operator because it has three operands. That's what ternary means. It doesn't mean any other operator involving a question mark is also ternary. –  Feb 18 '15 at 11:13

2 Answers2

5

it will assign an empty string to x if y is null

it is called null-coalescing operator.

for example if you have

a = b ?? c ?? d ?? e ?? f;

then it will look for b value. if it is not null then a=b if b is null it will check for c value. if it is not null then a=c. if c is null also then it will check for ... (go on)

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
2

This translates into the long statement.

if(y != null)
{
   x = y;
}
else
{
   x = "";
}
Adrian Salazar
  • 5,279
  • 34
  • 51