My Software Notes

Useful things I discover

Archive for April 2011

To var or not to var. That is the question.

leave a comment »

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.

(As an aside: Studying F# has made a big impression on how I code:  I tend to keep my variables immutable and declare another one if I am making a change – not 100% of the time as it would be impractical in my main languages (which, just now, are C#, TSQL and JavaScript), but probably 80 to 90%.  Another change caused by studying functional programming is that I am very aware of any side-effects my methods may cause and I try to write side-effect free methods and if they do cause side-effects I name them so it is clear that they do.  If you have only ever been exposed to OOP languages (like C#, Java, etc.) and procedural languages (like C, VB script, etc.)  I highly recommend studying a functional language.  It will expand your horizons.  In fact I recommend studying lots of different language types – more on that later.)

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.

Written by gsdwriter

April 21, 2011 at 8:46 am