Thursday, March 01, 2007

?? - C#'s Secret Operator

If you look at the MSDN documentation for ??, you might think that ?? is only useful for Nullable Types. However, it can be used with any non-value object.
So, in place of

return x == null ? default : x;

You can now write:

result x ?? default;

Cryptic? yes.
Wrist friendly? marginally.

I'm currently using an API that returns null instead of empty arrays. The basic construct now becomes:

ContentData[] dataToDelete = content.GetChildContent (folderId, false, "Title");
foreach (ContentData itemToDelete in dataToDelete ?? new ContentData[0] )
    content.DeleteContentItem( itemToDelete .Id);

This way I avoid NullReferenceExceptions, and get away without putting extra 'if' statements in.

No comments: