Friday, March 13, 2009

Tips 'n' Tricks - Null Coalescing Operator

We all like the null coalescing operator (, but it’s frustrating when we need to set the variable we’re returning rather than just returning it.

Really we just want to do this:

public class Something
private string falafel;

public string GetInfo()
return falafel ?? "tabbouleh";

But then falafel doesn’t get set.

This feels inelegant:

if (falafel == null)
falafel = "tabbouleh";
return falafel;

Luckily, there’s a solution:

return falafel ?? (falafel = "tabbouleh");

This first sets the value of falafel and then returns it.

No comments:

Post a Comment