Sunday, March 25, 2012

C# and ??

In C#, one can meet the operator made up of two question marks. This is known as the null-coalescing operator, and is used to check if a variable is null.  It works as follows.



myClass classInstance = gameObject.GetComponent("myClass.cs") as myClass;
myClass newVar =   classInstance ??  new myClass ();

The second line simply checks if classInstance is null. If it is, it will return a new instance of new myClass(); Else, it will return the classInstance itself. These lines are equivalent to the following:

myClass  classInstance  = gameObject.GetComponent(" myClass.cs ") as  myClass  ;
myClass newVar =  new  myClass  ();
if ( classInstance   == null)
  {
      newVar = new  myClass  ();
  }
else
  {
      newVar =  classInstance  ;
  }


 The beauty of it is that it is transitive, so one can write var a = b ?? c ?? d ?? e; 


No comments: