Showing posts with label null. Show all posts
Showing posts with label null. Show all posts

Thursday, July 19, 2012

Check if object is null

If you use the method below, 

public static implicit operator bool(Object exists){
       return exists == null;
       }

you can then use this code,
if (p2p){
}

instead of this code:

if (p2p == null){
}

Having said all that, this is a horrible idea, breaks C# conventions, and will create creepy bugs later on. So do not use it.

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;