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.

Wow that looks fake!

d20091010_0029

Water ripples as seen from the (docked) ferry at Tswassen on Saturday. I’ve often thought that procedural noise water textures in video games etc look fake, but they look an awful lot like this sometimes. So I guess they are accurate for some values of water.

Syntactic sugar: C# ‘var’ keyword

Learned this recently. In .NET 3.5, you can substitute ‘var’ for any type name that can be determined at compile time. So instead of typing (for example):

1
    Dictionary<MyKeyType, MyValueType> foo = new Dictionary<MyKeyType, MyValueType>();

I can instead just type:

1
    var foo = new Dictionary<MyKeyType, MyValueType>();

This isn’t the same thing as making ‘foo’ be of type object; foo is still strongly typed. You just don’t have to enter the type twice.

It’s a minor thing, but type names can get long in C#, especially if you use generics, and I like anything that reduces redundant code entry.

« Previous Page