Oct 22, 2009

Random Nerd Debates : Episode 2 VAR

In the second episode of Random Nerd debates we are doing to discuss the use of the C# keyword var.

First, what is var? MSDN has a very succinct explanation of the keyword:

“Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.”

And the simple code example:

var i = 10; // implicitly typed
int i = 10; //explicitly typed


Ok so now that we are both on the same page let’s talk about usage of this keyword. I have a very specific rule when it comes to the usage of var.



I will only use the var keyword to shorten my code without obscuring the clarity. This means I will only use the var keyword if the type can be inferred directly by viewing the right side of the operation. By “directly” I mean that the type is explicitly specified in the right side of the operation. I don’t want to have to jump to the method declaration or hover over the expression to determine the type. The best way to show this is through code examples:



//Since foo is clearly specified on the right side I WILL use var in this case
var foo = new Foo();

//Since the return type of the method GetBar() is not clear I WILL NOT use var in this case
var bar = GetBar();

//Other places where I WILL use var
var foo = (Foo)bar;
var bar = foo as Bar;


The benefit of the var keyword is allowing to write more succinct code. To me, succinctness can not come at the cost of clarity. In my examples above where I WILL use var I don’t feel like I am sacrificing any clarity but I am reducing noise.



There are two exceptions to my rule. When writing a LINQ query you almost always see the use of var and so I will follow that convention



var files = from file in enumerableFiles
select new Uri(file.FullName,UriKind.Absolute);


The other exception is similar to the LINQ example but more specific. There are cases which I want to deliberately de-emphasize the underlying storage mechanism and keep it ambiguous. In these cases I will use var to purposely obscure the underlying type. Eric Lippert explained this idea well in a blog post. The tidbit from Lippert was this:



   “Another subtle point here: notice how when I changed the type of the variable "racks" from "array of string" to "set of string", I didn't have to redundantly change the type thanks to implicit typing of local variables. I want to emphasize the semantics here, not the storage mechanism. If I felt that communicating the storage mechanism was an important part of this code -- because it has such a strong effect on performance -- perhaps I would choose to emphasize the storage by eschewing the "var"."



If you don’t already follow Eric’s blog I highly recommend it.



So I pose the question to you? Do you use var? Do you have a specific rule you follow when it comes to using it? Did you read this whole post and realize you just wasted the last 20 minutes of your life?

Labels: ,

5 Comments:

Blogger Joe Seymour said...

Part of my soul just died...

October 22, 2009 at 12:53 PM  
Blogger trent said...

Not only do I use var, but I can't wait for the dynamic keyword in 4.0. I prefer to stick with appropriate variable names. I'm getting on the bandwagon of deproceduralizating (hmmmm...) ala F#, Ruby, javascript, ect. Having a language that can infer things it should know (like type) and go beyond the elements of a static language should be of interest, and dev's should know when and how much to use.

November 16, 2009 at 4:13 PM  
Blogger Thomas Eyde said...

I don't get it. I see you pro's and con's, but still I see the same thing. To me, all your arguments concludes with var as the best option.

I always use var, except when I can't: And that's where it's not allowed, or when it evaluates to object when a specific type is needed.

If I need to do:

IVehicle car = GetCar();

Then something is very wrong. I should need to consider the car as an IVehicle or as a Car, but not both at the same time.

When I see code like this, I see a method name clearly out of sync with its return type. Or a method body with unclear intentions.

November 20, 2009 at 4:25 AM  
Blogger Brad said...

Thomas, I agree with the principal of your argument that clarity is of utmost importance in your code. That being said, the point of my post is that you can use var in a way that increases code clarity by decreasing useless noise (i.e. redundant type information)
As I show in the post, there are time when using var obscures your code. While, in a perfect world, I would agree with you, the use of clear method names would mostly eliminate the need for type information. In reality that isn't the world we live in.
IMO type information is far more useful than method or variable names. People just don't always name variables or methods clearly. What is clear, in a strongly typed language like C#, is the type. No matter what your method is called the type is what it is. Obscuring the type by doing
var car = GetCar();
slows me down. But reducing redundant type information by doing:
var car = GetCar() as IVehicle;
Make my life easier. In the end it is all personal preference and what works for you doesn't always work for other people.

November 20, 2009 at 7:29 AM  
Blogger F Quednau said...

Since this is called nerd debates one should add that the use of var in LINQ statements is also due to the fact that anonymous types exists. When writing
var result = from c in Customers select new { c.Name, c.Age }
You do not want to be bothered with the actual type name of the returning instance.

January 14, 2010 at 3:44 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home