Friday, January 18, 2008

Using var in C# 3.0

I hadn't really read much about the new var keyword in C# 3.0 but it had troubled me. I had assumed it was like the var keyword in JScript and meant C# was turning into a late-bound dynamic language which I really wasn't keen on. As I mentioned previously, this can cause problems in JScript.NET when the compiler can't infer the type.

So I was pleased to see that the IL generated by this is still the same as if strongly-typed variables were used and if the compiler can't infer the type from the code, it won't compile. But there's still something of a problem. The addition of this new keyword means that coders can now just declare every local variable using it (fortunately not member variables) which will lead to less clear code. Explicit declarations are good, there's no question what is going on.

And I just know in a few months/years time I'm going to be looking at some code I have to maintain and I will be swearing under my breath and asking why some pillock declared everything using var.

No comments: