14 December 2010

Everybody knows the ternary operator ?. It can be found in most languages like C/C++, Java, C#, PHP and JS. But how many C# developers know about the binary operator ?? ? Apparently not so many.
?? is a great little thing introduced along with null-able types in .NET 2.0. It's meant to eliminate some ifs in your code when working with types that can be null. Unfortunately it is not so widely used.
Let's check an example:
[csharp]
int GetTeamPoints(User user)
{
int? teamPoints;

using (DBDataContext db = new DBDataContext())
{
teamPoints = db.Users.Where(x => x.Team == user.Team)
.Sum(x => x.Points);
}

if (teamPoints == null)
teamPoints = 0;

return teamPoints.Value;
}
[/csharp]
The code works ok, but how about the next example:
[csharp]
int GetTeamPoints(User user)
{
int? teamPoints;

using (DBDataContext db = new DBDataContext())
{
teamPoints = db.Users.Where(x => x.Team == user.Team)
.Sum(x => x.Points);
}

return teamPoints ?? 0;
}
[/csharp]
Ah, now it looks so much cleaner. And it's faster by a few processor cycles.
Although ?? has been introduced especially for working with nullable types, it can work with reference types as well, returning a value when the object is null.

You may want to check the MSDN reference: ?? Operator (C# Reference)



blog comments powered by Disqus