Thursday, May 21, 2015

C# - The ?? och ? operator

Null-coalescing operator - ??

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. An example of this:

 int value = (int)(CurrentPage["MyDynamicPropety"] ?? 0);  

And another:

 CurrentPage["CardImage"] != null ? CurrentPage["CardImage"].ToString() : String.Empty;  

See: http://msdn.microsoft.com/en-us/library/ms173224.aspx

Conditional operator - ?


TRUE FALSE Condition ? First_expression : second_expression;

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
Following is the syntax for the conditional operator. The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result.
Only one of the two expressions is evaluated. Another example of this:

 h1Ctrl.InnerText = IsValue("Heading")  
                     ? CurrentPage.Property["Heading"].Value.ToString()  
                     : CurrentPage.PageName;  

No comments:

Post a Comment