C# operator I didn’t know: ??

Tags:
Add comments

I didn’t know how this could happen. There’s a operator part of the language I love and I didn’t see it anywhere till today. I think many of you didn’t knew about the ?? operator either. And by the way: it is part of C# since C# 2.0!

How often do you write code like this?

string a, b;
if (a == null)
    b = "some default value";
else
    b = a;

You have to check for null and use some default value if your object is null. The code can be written a little bit shorter with the ?: operator:

b = (a == null) ? "some default value" : a;

It’s nice but with the ?? operator it is much cooler:

b = a ?? "some default value";

Let me quote the msdn library: "The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand."

You can use this operator with every object type and with every nullable type (like int?).

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in