Friday, August 19, 2011

?? operator in c# || null-coalescing

Hi,
This little comment on ?? operator in c# will give an idea how to use it.


You cannot assign NULL to any value type in c#
Is there any way to assign null to Int.The answer is NO.
For example:
           int x = NULL; //Error as you cannot assign null to a non-nullable type
instead you can use like this,
           int? x = NULL; //Runs Without error


What happens if x is assign to a variable of type int?
          int y = x; //Error
          int y = (int)x; //Error
Even if i cast it to int it wont allow to set the null to y,


Now the ?? comes into he picture.


        int y = x  ??  5;
Here,the value for x is checked (if x is null then it will assign 5 to y);
        now y will contain 5;
Suppose if i want to set the value of x you can do it ,Just simply assign x = 90;
and now,
        int y = x  ??  5;
Here the value for x is not null so the value of x is assigned to the y .
        now y will contain 90;



No comments:

Post a Comment