Thursday, 10 December 2015

Nullable conditional operators example in c#

To check null condition in small line of code we could use nullable conditional operators that is ? and ?? (Coalescing Operator). Single question mark ? and double question marks ?? expression.

Response.Write(Request["a"] ?? "");
Response.Write(Request["a"] == null ? "no" : "yes");
Response.Write(Request["a"].ToString());


Response.Write(Request["a"] ?? "");
default.aspx
output :

default.aspx?a=raj
output : raj

Response.Write(Request["a"] == null ? "" : "yes");
default.aspx
output :

default.aspx?a=raj
output : raj

Response.Write(Request["a"].ToString());
default.aspx
output : Error Object reference not set to an instance of an object.

default.aspx?a=raj
output : raj

How to use nullable operators with . dot in c#?

int? length = customers?.Length; // null if customers is null
Customer first = customers?[0];  // null if customers is null
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null

Reference:
https://msdn.microsoft.com/en-us/library/ms173224.aspx
https://msdn.microsoft.com/en-us/library/dn986595.aspx