Search code examples
c#operators

c# operators '??' and 'as'


I saw this code but i don't know order of operators in second line. What's result of second line?

Object obj = 1;

String s = obj as String ?? "";


Solution

  • C# operator precedence table states that as (see "relational and type-testing" row) operator has higher precedence then null-coalescing operator (??), so your expression will result in empty string, because obj as String will evaluate to null thus null-coalescing operator will return right-hand operand, i.e. "".