C# ?? Operator

Recently I found a new operator in C#, which is ??. Its more compact than Ternary operator (?:).Ternary operator is short form of if else and ?? is also kind of if else, but its work with null value an one assumption.

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type.

Example:
int x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
string sUserName=null;

//using if else
if(Session["UserName"]==null)
   sUserName=string.Empty;
else
   sUserName = Session["UserName"];

//using Ternary Operator (?:)
sUserName=Session["UserName"]==null?string.Empty:Session["UserName"];

//using Null-Coalescing Operator (??)
sUserName=Session["UserName"] ?? string.Empty;

Note: The result of a ?? operator is not considered to be a constant even if both its arguments are constants.


Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment