C# 2.0 has a nice ?? operator that works as a shortcut for:
string value1 = null;string value2 = "Test1";string result = value1 != null ? value1 : value2;
which causes result containing Test1 or the second value.
In C# you can shortcut this special null comparison case with the new ??:
string result = value1 ?? value2;
This operator is called the null-coalescing operator.
you can chain these operators together so you can do a whole bunch of null comparisons in a single stroke.
For example, We frequently look for a few different querystring variables in a page:
///// Generally programmers do like this
if (Request.QueryString["RP"] != null)
{
qrystring = Request.QueryString["RP"].ToString();
}
else
{
qrystring = "I am blank";
}
//The above If-Else version can be written in one line :
qrystring = Request.QueryString["RP"] ?? "I m blank";
//Another version with Multiple quertystrings which removes the usage of Multilple Nested Ifs:
string partner = Request.QueryString["GoogleId"] ??
Request.QueryString["PartnerId"] ??
Request.QueryString["UserKey"] ??
string.Empty;
which still yields a valid result for the first non-null querystring or if nothing is found returning "".
The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.
A good trick using the null coalesce operator (??) is to automagically instantiate collections.
private IList
_foo;
public IList ListOfFoo
{
get
{
return _foo ?? (_foo = new List());
}
}