Monday, August 14, 2006

cool use of the coallesce ?? operator in C#

We just coded something like (please disregard the variable names, I'm just illustrating the point)

return myCollections.Services ?? (myCollections.Services = dbLayer.GetServices());

one-liner to do a bunch of stuff, and it's still clear what you are trying to do, if you know the ?? operator you can stop right here, if you don't let me explain a bit more

the ?? operator returns the left-hand operator if it is NOT NULL, else it returns the right operand

so this code is the equivalent of:

if (myCollections.Services == null)

  myCollections.Services = dbLayer.GetServices();

return myCollections.Services;

No comments: