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)
19 Nov 2009 1  
I agree that in the above example, the use of var is a bit excessive. However, for very long types (such as a dictionary with the key and value both being lists of some nested classes... see below code example), this might actually improve readability (seeing so many details may overwhelm you). Assu

I agree that in the above example, the use of var is a bit excessive. However, for very long types (such as a dictionary with the key and value both being lists of some nested classes... see below code example), this might actually improve readability (seeing so many details may overwhelm you). Assuming the method and variable are named well, you should have a general idea of what is returned. And, you can mouse over the "GetData" method to see what the return type is.

I'd say var in the example you give would be useful for long types but not very useful for short types. However, it wouldn't slow you down too much... if you really need to see what the type is, just mouse over the method.

C#
// Readable, but must mouse over method to see type returned.
var x = GetPairs();
// Readable, but distracting.
Dictionary<List<Animal.Dog>, List<Animal.Cat>> y = GetPairs();

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