“Really Smart” Type Inference in C#3.0


At least I think that this was added in C# 3.0 – “implicitly” typed arrays.

Imagine this simple scenario:

IEnumerable <string> myStrings;

Now imagine that we wanted to assign “Isaac” and “Daniel” to that reference. We could do it in a number of ways: –

IEnumerable <string> myStrings = new List<string> { “Isaac”, “Daniel” };

 

This uses Object Initialisers which aids readability, although we’re being a bit lazy using a List<T> for such a simple collection.

We could rewrite it as this: –

IEnumerable <string> myStrings = new string [] { “Isaac”, “Daniel” };

 
This defines an array of strings instead of a List<T>. Whilst we’re at it, let’s remove the type on the left hand side.

 

var myStrings = new string [] { “Isaac”, “Daniel” };

However, there’s actually one further step that we can take to simplify this:

var myStrings = new [] { “Isaac”, “Daniel” };

My first thought when I saw this was “huh”? Where’s the type definition – it’s not on the left OR the right hand side??? The answer is, of course, that the compiler infers the type based on the content of the object initialiser. There’s only so far you can take this though – you can’t do this: –

var myStrings = new [] { “Isaac”, 2 };

Although you can do this:

var myStrings = new object [] { “Isaac”, 2 };

They’ve made some really nice, logical changes to C# since 3.0 which makes our code much more readable and logical, at no expense of type safety… this is another example.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s