Every once in a while, you run into something that makes you go “damn, I wish I knew that before.” In this case, I was given a lesson by the wonderful Resharper.
I had a variable that I wanted to have a default value if it was null. So, I figured something like this would work:
x = (x==null) ? "1" : x;
If x is null, it will be given a default value of 1.
Resharper corrected me to this:
x = x ?? "1";
“What the heck is that operator?” said past me. Answer:
“The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.”
In other words, if the left side of ?? is null, the right side is returned.