Steve Wellens

Programming in the .Net environment

Sponsors

Links

Can the C# ‘var’ Keyword be Misused?

More and more often I've been seeing C# code like this:

var Data = GetData();

What on earth does GetData() return? This code is not as maintainable as it could be and is not as maintainable as it should be.

Doesn't explicitly declaring the variable type make the code more readable, understandable and ultimately more maintainable?

DataTable Data = GetData();

Ahhh, GetData() returns a DataTable.

I know that var has uses but I wish it would have been named something much longer because typing 'var' is too easy. Perhaps it should have been named AutomaticTypeVar or even AutoVar to reduce the lazy misuse.

Just my 2 cents.

Steve Wellens

[Update]

A user on the Asp.Net forums was kind enough to provide this quote and link:

"However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required."

http://msdn.microsoft.com/en-us/library/bb384061.aspx 

 

 

Posted: Nov 19 2009, 07:52 AM by SGWellens | with 27 comment(s)
Filed under: , ,

Comments

Ruud van Falier said:

I fully agree with you here.

I've seen alot of misuse of the var keyword in source code from co-workers.

One of the first things i do when i get to work with that code is replacing all the "var" with the exact datatypes.

The best thing to do, in my opinion, is to never use this keywords unless it is mandatory.

/Ruud

# November 19, 2009 10:02 AM

AndrewSeven said:

The GetData method name used in you example is worse than the use of var.

If I couldn't get that method fixed, I would tend to declare the type.

# November 19, 2009 10:28 AM

SGWellens said:

>> The GetData method name used in you example is worse than the use of var.

It is a contrived example to illustrate a point.

In a real application I would not give a method such a bland meaningless name.

# November 19, 2009 10:33 AM

zoldello said:

It is not Microsoft's fault that developerx choose to abuse useful and powerful tools. I think "var" is excellent. My rule of thumb is that if you do not know how to use it then limit usage to LINQ.

# November 19, 2009 11:51 AM

paul.vencill said:

I couldn't disagree with you more.

explicit typing is useful if you're writing apps in Notepad, but with an IDE that lets you hover and inspect, it's no more maintainable than var, ime.

A well-named method buys you a lot more analyzability than explicit typing does, and using 'var' provides a lot more flexibility during refactoring and other code-maintenance tasks.  

And in the case of static code reviews, does it *really* matter whether GetCustomerOrderHistory() returns a DataTable or an IList<Order>, or whatever?  More specifically, does it matter *in the context that var was used* or is that something you can cover when you are reviewing that actual method?  

again, ime, the answer is 'no'.  You can logically follow the app's intent w/o the explicit typing.

# November 19, 2009 11:52 AM

aa said:

Bad users will always misuse good tools, anyway.

var dtUsers = GetUsers();

Is that a misuse?

# November 19, 2009 11:59 AM

Gianluca Gravina said:

My 2 cents:

First : If possible refactor the method name !

Second : If useful, declare the type, but only if it's useful

GG

# November 19, 2009 12:29 PM

AndrewSeven said:

>> In a real application I would not give a method such a bland meaningless name.

And in such a case, the use of var might not be so bad.

This is something that is useful but is easily subject to abuse. Those who are inclined to abuse it would not be discouraged by it having a longer name.

I've seen people use it very badly: var helloMessage = "Hello World"; var terrible=true;

I've also seen it simplify some complex refactoring where the type was unimportant within methods and because they used var, those methods did not need to be changed.

# November 19, 2009 1:52 PM

Ravi Terala said:

I don't agree with the author. If you can't understand what the intent of the code is by looking at the naming conventions, etc, you have a much bigger issue of code getting messier.

I would say if you can't figure out what the code does from the variable names and function names, its time to refactor code until it starts becoming intuitive. 'var' helps a lot in this regard.

# November 19, 2009 2:02 PM

valamas said:

var sucks = true;

Coders with poor refactoring skill/motivation will make code look like soup when given the chance to use var.

# November 19, 2009 6:06 PM

SGWellens said:

I'm surprised some would argue that the function name is important...the variable name is important...but the type name, why it doesn't matter at all!

The more information you can convey with the code text, the more maintainable the code will be.

Perhaps some are guilty of using lazy short-cuts and are trying to defend them.  Shame on you!  :)

# November 19, 2009 7:05 PM

Brad said:

I agree with your position on var. In fact I posted a blog, like you, about this very topic.

I have some very specific rules about the usage of var.

www.bradcunningham.net/.../random-nerd-debates-episode-2-var.html

# November 19, 2009 7:49 PM

Mark Nijhof said:

I would say make your variable name more descriptive, that is much more valuable. That way everywhere you use the variable you can read what it means. Also the implementation is much less important then its intent.

# November 19, 2009 8:12 PM

Jared said:

So you're saying that the use of "var" in the example harms the code clarity more than the poor function and variable names? Sorry, not buying it.

# November 19, 2009 8:34 PM

SGWellens said:

>> So you're saying that the use of "var" in the
>> example harms the code clarity more than the poor
>> function and variable names? Sorry, not buying it.

No, I am not saying that.

I'm saying descriptive names improve maintainability.

# November 19, 2009 8:55 PM

Mikael Lundin said:

I use the var keyword to reduce noise from my code, because most often, the variable type could be considered noise.

As said above, using var should not change the readability of the code. The purpose by using a good variable name and the method name must be much clearer.

Sometimes though, you don't want to use var. When you want to make clear that the variable is a base type of an interface.

IPerson person = new SuperHero();

But I love to use it in a foreach where it is just noise to print out the type of the item.

foreach (var person in persons) { .. }

# November 20, 2009 12:02 AM

Hadi Hariri's Blog said:

var improves readability

# November 20, 2009 2:11 AM

Hadi Hariri said:

&#160; Countless times I’ve heard the argument that you should use the var keyword with caution, that

# November 20, 2009 2:12 AM

Mattias Jakobsson said:

I agree with "paul.vencill" on this one. As long as you use any tool other then notepad (or similar) then why do you need to know what type you are actually using? Isn't the methods the important thing? Doesn't visual studio help you there?

If you really need to know the datatype, then just name your variables and methods properly and it's all solved.

Another common misunderstanding I see a lot is the one "Mikael Lundin" describes. IPerson person = new SuperHero();. How is that better then var person = new SuperHero();? You still have a dependency on the class SuperHero, thats a fact. So that will gain you exactly zero advantages. You can still use it in any method that takes a IPerson.

I use var everywhere. And it gain me a few advantages, like easier refactoring, while it has no disadvantages.

My answer to the question is: No, var can not be misused. If you need to declare the type to be able to read the code, you are doing something wrong.

# November 20, 2009 2:17 AM

nicstrong said:

var dataTable = GetXAsDataTable();

1) Method name hints as to type.

2) Is now more discoverable using intellisence.

3) Variable name hints to type even if declaration is not in displayed.

# November 20, 2009 2:33 PM

SGWellens said:

>> var improves readability

Sure it does and o and l make good variable names.

It's surprising that some who use var where it's inappropriate would dedicate any energy to defending the lazy practise.  Maybe 'bad-code-guilt' is providing the impetus.  :)

# November 22, 2009 12:37 PM

Neal Blomfield said:

Now step back and look at var in the light of dynamic languages...

# November 22, 2009 2:12 PM

Ryan Ternier said:

The problem comes in when using black-box controls/libraries.

If monkey A wrote a method GetUserList, and someone just used Var users = GetUserList();  that looks like poo. I'm sorry but it does. Writing List<users> users = GetUserList(); doesn't take much time. The last thing I want is my code to look like some JavaScript flunky got lose in our office.

# November 23, 2009 11:53 AM

andreas said:

C# should have used var only when you can't explicitly give the type name.

people who like var, the C# 4.0 dynamic or whatever, why not use some other language within the .net framework?

why should c# take the middle ground of trying to please everyone and support all programming styles, wasn't the .net framework itself supposed to provide that flexibility?

# December 15, 2009 6:21 AM

Rafael said:

Perfectly right! var is for kids. But the community has remembered well: the method must be meaningful.

# January 11, 2010 9:02 AM

Nick said:

All good points, just my 2 cents to follow. I hate var, I hate it with a passion - I hate the fact I have to use it for anonymous types, even! That aside, I had to have this discussion with colleauges who loved (and overused) it. Our working rule was:

"If a human can't immediately infer the type, then the compiler shouldn't." So...

var s = "hello, world!"; is OK (I still hate it...)

var buidler = new StringBuilder(); is OK

var data = GetData();    is NOT OK

And this rule stands for us REGARDLESS of how well a method/property is named, to avoid subjectivity and arguments. Besides, things should be named well regardless, and var does not fix naming conventions.

# September 7, 2010 2:51 AM

Fabulous Adventures In Coding said:

One of the most controversial features we've ever added was implicitly typed local variables , aka "var

# April 20, 2011 1:38 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)