Learn IT

Free learning anything to everything in Information Technology.

C# Coalesce

Although this has been around for a long time and this is slightly off topic, I needed it this week, and just think it is worth mentioning. With objects you occasionally need to know if they are null, and if they are get something else, or do something else. This used to be very convoluted with .NET 1.1:

if (a != null)
{
return a;
}
else if (b != null)
{
return b;
}
else if (c!= null)
{
return c;
}
else
{
return new object();
}


Now you can simply use this (.NET 2.0 and above):

return a ?? b ?? c ?? new object();

Now you can not use this with types that get default values, such as Integer's, or boolean's, however still very usefull.

0 comments: