Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Can the C# ‘var’ Keyword be Misused?

0.00/5 (No votes)
21 Jul 2011 1  
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.

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

C#
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?

C#
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 

 

[Update II]

There seem to be a lot of lazy developers who are trying to justify and rationalize their lazy habits. 

Let's try a heuristic approach to see if the concept of maintenance can be better communicated:

C#
var x = FunctionA();              // this is unacceptable

var x = GetCustomerID();          // better

var CustID = GetCustomerID();     // better but what is CustID?

String CustID = GetCustomerID();  // best.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here