0

The code is as follows:

if(f1) 
{ 
    return a1?.a2 ?? a3 
}

Can anyone tell the use of these operators here?

spender
  • 117,338
  • 33
  • 229
  • 351
Sandya
  • 5
  • 2
  • http://stackoverflow.com/questions/7331686/why-and-not – A user Feb 23 '17 at 16:39
  • 1
    Possible duplicate of [Why && and not &](http://stackoverflow.com/questions/7331686/why-and-not) – A user Feb 23 '17 at 16:39
  • return a1?.a2 ?? a3 a1 can be null. If it isnt, then it will return a2. If both are null, then a3 is returned. https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx https://msdn.microsoft.com/en-us/library/ms173224.aspx – TheNoob Feb 23 '17 at 16:40
  • 3
    [Null conditional operator](https://msdn.microsoft.com/en-us/library/dn986595.aspx) and [Null coalescing operator](https://msdn.microsoft.com/en-us/library/ms173224.aspx) – spender Feb 23 '17 at 16:41
  • 2
    `?`= null-conditional operator, `??`= null-coalescing operator. – MakePeaceGreatAgain Feb 23 '17 at 16:42
  • @TheNoob: `?.` binds tighter than `??`, so if `a1` is non-null but `a1.a2` is null, `a1?.a2 ?? a3` will return `a3`. And note that there isn't just an "a2" - there's "a1.a2`. – Jon Skeet Feb 23 '17 at 16:44
  • @JonSkeet I was trying to explain that but you did it better. xP And omg Jon Skeet replied to me =O You helped me way too many times from your answers on SO. Heres my shot to say Thank you! =) – TheNoob Feb 23 '17 at 22:38

1 Answers1

2

first the operator ?? example:

var c = a ?? b;

is equivalent to

var c = a == null ? b : a;

the second one ?. it is to not throw NullReferenceException example:

var c = a?.Name;

is equivalent to

var c = a == null ? null : a.Name; 

it is short cuts to avoid ifs and long lines

Did you get it ?

Hugo Jose
  • 339
  • 2
  • 13
  • One important thing to note on primitive types at the end of a long ?. is that they are all turned into Nullable Types. Which means you can't compare directly with certain values. You may have to use .GetValueOrDefault(), or some of the other Nullable functions. – thinklarge Feb 24 '17 at 15:13