uncategorized

C# 3.0 and the var type

Back in the good old days when I was programming in VB6 we had this data type called variant.  Basically we could use it for anything we wanted to as long as we were comfortable with weak typing.  Some people liked this a little more than others as I recall.  In one instance I inherited an application where _variant _was the only variable type that was used.  Thankfully variant disappeared from the world with the inception of the .NET framework.  Since .NET 1.1 we’ve been living in a strong type world that provides us with wonderful compile time validation of our coding.  In case you can’t tell, I love strong typing.

Well, with C# 3.0 the variant datatype comes back with a couple of important twists.  First, it’s not called variant, but rather var.  I suppose there were some bad connotations still tied to the term variant, but really the name change is indicative of the bigger differences between variant and var.  The biggest difference is that var infers the datatype when it is being used.  In the image below you can see that the varCust variable is showing the properties that belong to the Customer object.  varCust has inferred that it’s type should be Customer based on it being set to equal the cust variable which is defined as type Customer.  If you look at the image on the right, which was taken from disassembling the compiled code using Lutz Roeder’s Reflector tool, you’ll see that the compiler simply changes the var typed variable to a Customer type at compile time.  Another way to see this is to hover over the varCust variable definition when it’s being used and the tool tip will display “(local variable) Customer varCust” (sorry no image as my software won’t keep the tool tip open during capture).

varstrongtypingvarstrongtypingdisassembler

Because the datatype is undermined until the variable has been initialized, you can not compile your application without doing the initialization.  This also makes sense when you consider that the compilation has changed the var type to a Customer type.

varstrongtypingnoinitialize

Another difference between var and variant is that once you’ve initialized a variable typed var, you can’t change it’s type.  In the example below I’ve initialized varCust to a Customer type and then try to set the varCust to a value of type Employee.  Unlike variant, the compiler simply doesn’t let you do this.

varstrongtypingchangetypes

 So what does this mean for you the developer?  Well, not a whole lot quite frankly as var is nothing more than syntactic sugar.  I think that the most prevalent use the var type is going to see is as a quick and dirty way to get a variable created.  It will be used by lazy programmers for this purpose more than anything else.  I think that we will be back to the days of looking at variant based variables again, but this time at least we will have strong typing to back us up.