C# Tips - Null Coalescing ??
I have always enjoyed using the logical OR operator in JavaScript (||
) as an oppurtunity to check for a null-like value, specifically to provide default parameters for functions or to check for existence of a property on a collection. I think they are a great way to make code more concise, and if used well, more readable.
These two functions do the same thing, but the first is shorter and more readable to people who may have to go back and modify it later.
function contentDocument(frame) {
// If the frame.contentDocument either doesn't exist or is a null
// value, it will skip to the next value down the line
return frame.contentDocument ||
frame.contentWindow.document ||
frame.document;
}
function contentDocumentVerbose(frame) {
// This works, but is possibly too verbose for such a simple task
if (frame.contentDocument) {
return frame.contentDocument;
}
else if (frame.contentWindow) {
return frame.contentWindow.document;
}
else if (frame.document) {
return frame.document;
}
}
I was happy to see that C# has a similar feature, the Null Coalescing Operator.
This is nice for the same reasons, and is more readable than the normal ternary operator when simply checking null. Of course, if I am not checking for a null value, but a more complex boolean expression, I will usually use the ternary operator or an if-else block it is more than just a variable assignment or return statement. Anytime I use any extra syntactical feature, it is my hope to make the code more readable.
Anyway, here is an example of the ??
(coalescing) operator contrasted with the ?
(ternary) operator.
string APP_DEFAULT = "application/octet-stream";
private string GetContentType(string contentType)
{
// Nice and readable. The '??' operator can be very useful.
string FUNCTION_DEFAULT = null;
return contentType ?? FUNCTION_DEFAULT ?? APP_DEFAULT;
}
private string GetContentTypeTernary(string contentType)
{
// This is NOT readable. Please do not use nested ternary
// operators... They take too much energy to figure out.
string FUNCTION_DEFAULT = "text/plain";
return (contentType != null) ? contentType :
((FUNCTION_DEFAULT != null) ? FUNCTION_DEFAULT : APP_DEFAULT);
}
November 21st, 2011 at 8:56 am
Great fan of your site, a variety of your blogposts have really helped me out. Looking towards upgrades!
May 1st, 2012 at 1:09 am
Click Here…
[…]below are a few links to internet sites which we connect to seeing that we believe they really are definitely worth browsing[…]…