May 25, 2011

The C# ?? null coalescing operator on value and reference type


In C#  "??" operator is known as null coalescing operator. It can be used on both nullable value type &  reference type.
?? operator checks if  the value provided on the left side of the expression is null, it returns value on right side of the expression. if its not null it return the value of the left.
Q. how the value type will have null.
A. With nullable type. int? a = null;

Example 1:
string str = null;
string output = str ?? "Punjab";
------------------------------------
output = "punjab"
because str is null, 
--------------------------------------
Example 2.
string str = "Punjab";
string output = str ?? "Delhi";
------------------------------------
output = "punjab"
because str is not null, 
--------------------------------------

Example 3.
int test?=null
int output = test ?? 164;
------------------------------------
output =164
because test is null, 
--------------------------------------

No comments: