My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com









Friday, June 29, 2018

Null conditional operator : Question mark (?) before Variable

One of the reader recently asked about the new kind of operator that we use in C# 6.0. He noticed that in the VS - 2015, there is a use of new operator as following. And, he wanted about what it is:
Eg: public class A {
   string method1 { get; set; }
}
..
var a = new A();
var foo = "anwar";
if(a?.method1 != foo) {
   //somecode
}

So, let me explain this brief concept!

It's the null conditional operator. It basically means to evaluate the first operand. If that is null, stop, with a result of null. If not, evaluate the second operand as a member of the first operand.

In the above example, the point is that if a is null, then a?.method1() will evaluate to null rather than throwing an exception.  It will then compare that null reference with foo, using string class overload, and find that they are not equal and execution will go into the body of the if statement.

In addition, it can be very useful when flattening a hierarchy and/or mapping objects. iEg, Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "default"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "default";

So, with this I end. Go, grab a cuppa coffee. I will still do Cheers :)