Implicitly typed arrays in C# 3.0

Please excuse the short post and general quietness on my blog, but am typing with a newly installed, titanium screw through a tendon and fractured bone of my finger (fixing an "avulsion of the distal phalanx" apparently)*.

ReSharper 4 just found me another little C# 3 feature to save a bit of typing (handy** given my current condition ;-)). First, let’s start with a basic array declaration and initialisation:

Person[] people = new Person[] {new Person("Ann"), new Person("Bill")};

Now C# has the new var keyword to get the type from the right hand side of the assignment:

var people = new Person[] {new Person("Ann"), new Person("Bill")};

But it also has implicitly typed arrays***, which means we can write this:

var people = new[] {new Person("Ann"), new Person("Bill")};

As with var, the compiler is clever enough to strongly type the array appropriately from its initialisation. All three examples are functionally equivalent.

Sure, only a minor impact on the amount of typing you do, but the main benefit is reducing the noise surrounding your code and making it easier to get the intention of the code. (I’m currently trying to learn Python, and am getting an appreciation for removing unnecessary noise – I’m even liking the whole "significant whitespace" thang :-) )

* Basketball is not a contact sport
** Excuse the pun
*** This link gives a really good overview of the new C# 3.0 features

Comments