What the ??

Or, alternately, you learn something new every day

There's an ?? operator in .Net and I just found it to be the most helpful thing.


The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.


string xyz = null; 
string abc = xyz ?? "XYZ was null";

would have abc = "XYZ was null";

where as

string xyz = "Hello"; 
string abc = xyz ?? "XYZ was null";

would have abc = "Hello";

This works on any object. I discovered this because I was trying to sort some data based on an integer field called Rank. However, the field is not required so nulls were showing up at top, rather than at the bottom which isn't what I wanted. So I ended up with this LINQ query

from categories in context.Categories  
where categories.Active == true
orderby categories.Rank ?? int.MaxValue
select categories;

What this does is order the categories by their rank, unless the rank is null, in which case it's set to the highest possible value (ensuring it'll be at the end).

Pretty nifty, so I thought I'd share!

posted by by Robb Allen @
Comments have been closed on this topic.