Archive for April 2011
You can always use or misuse or overuse Shakespeare to make a point. Hopefully this is an example of “use” and not “misuse”. 🙂
Somewhere on this blog I posted about using “var” in C# (“var” is a pronoun). In it I said you should only use it when it was obvious what the data type is. Well, I’ve changed my mind. What can I say? Times change, people evolve, live with it.
I now use “var” all of the time. I rarely, if ever, don’t use it. If I am declaring a variable and setting it to null then I will explicitly name the data type, otherwise it’s “var”.
Why the change? The first thing that led to it was some study of F#, which does implicit typing all the time. Even if you don’t assign a value to a new variable the compiler will still figure out what the type is based on what you do with it later in your program. Very nice.
But back to the point. So, studying a functional language that has implicit typing and seeing the advantages of that was the first reason. The second reason was laziness. The third and (for me) most important reason was that I really wasn’t gaining anything by explicitly naming the types. Honest, in the years that I’ve been using “var” I have never had a problem figuring out a bug or how to modify some existing code because I used “var”. So why would I not use it? The fourth and final reason was that I can change the type of something and not need to change assignment statements. E.g., var myVar = SomeMethod(); If SomeMethod returns a bool and I change it to return a string – I don’t need to change that assignment statement.
If you need a deeper analysis of this then read Eric Lippert’s excellent article: Uses and misuses of implicit typing. Or just start using “var” and see for yourself if it ever causes a problem.