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.

Comments are closed.