More C# syntactic sugar

First up, the “??” uperator. You’ll probably suspect that this is related to the ?= ternary operator, and you’d be right. The ?? operator is called the null-coalescing operator. Not a very meaningful name, but here’s what it does.

1
foo = bar ?? baz;

is equivalent to:

1
foo = (bar != null) ? bar : baz;

and also to this, which I usually write because I find the ternary operator ugly:

1
2
3
4
5
foo = bar;
if (foo == null)
{
    foo = baz;
}

Also discovered recently: extension methods. Not having private access is a bit of a drawback, though I can certainly understand why that is. It amounts to a convenient way to write helper code for awkward APIs.

Comments are closed.