Saturday, June 11, 2011

Implicitly typed variables

Recently I got into a discussion about implicitly typed variables in C#. It was my fault, I asked others for their opinion :). The general observation was that implicitly typed variables are mostly syntactical sugar and a sign of lazy coding. Except, of course, when you use anonymous types.

There is however an other, and I think very valid, reason to use implicitly typed variables that goes beyond anonymous types or lazy coding (yes ... lazy coding can be a valid argument :) ). In short: implicitly typed variables allow you to make the weakest assumption about the type of the variable. And one common problem in applications is making stronger than needed assumptions and copying those assumptions across your code.

To give a more concrete example:

var s = myObj.GetValue();
string myText = s.ToString();


int s = myObj.GetValue();
string myText = s.ToString();

In the first we only require in our code that the value returned by GetValue() implements ToString(). In the second, we actual make the much stronger assumption that GetValue() will return an integer. If that return value is ever modified to be a real, we will need to modify the second implementation, even though the fact that we changed from integer to real did not impact what the code does.

To give a second example:

string[] values = anObj.GetValues();
foreach(string s in values) {}


foreach(var s in anObj.GetValues())

The second implementation only requires the return value of GetValues() to implement IEnumerable. The first requires GetValues() to actually return an array of strings.

To recap, I think implicit variables have a valid use. I have always felt that if a language has a feature, there must be strong reasons for barring it from your code. I don't see a strong reason to bar implicitly typed variables from code. I actually see some advantage in using implicitly typed variables when you look at assumptions and contracts in your code.

No comments:

Post a Comment