C# type inference

While I work mainly in a Java shop, I continue to be impressed by what Anders Hejlsberg, chief architect of C#, brings to the table to a language which in my mind has always represented Java done right. I do wonder however, how come they did not take the concept of type inference just a little bit further.

Local variable type inference
This feature of C# 3.0 basically allows you to omit the declaration which, especially when generics is involved, causes a lot of repetition and long lines of code:

Dictionary<int, IEnumerable<decimal>> myCollection =
new Dictionary<int, IEnumerable<decimal>>();

Which can be reduced to this:

var myCollection = new Dictionary<int, IEnumerable<decimal>>();

No late binding is taking place, the compiler simply infers the actual type and substitutes var with it.

No method return type inference?
Some languages operates with the concept of tuples, a way of returning multiple values without having to wrap them in an array and use casting or a predefined data transfer object. Wouldn't it be nice, if we could use type inference here instead to be able to return multiple values from one invocation - and still be type-safe about the whole thing:

var getInferredType()
return new {X = 22, Y = -3};

var coordinate = getInferredType();

Perhaps this isn't doable for reasons of method signature lookup or polymorphism rules, I don't know. But it strikes me as something that would be very usefull and further reduce the need of temporary housekeeping objects.


Popular posts from this blog

Beware of SQLite and the Turkish Locale

Rejsekort Scanner

@SuppressWarnings values