Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Can the C# ‘var’ keyword be misused?

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
19 Nov 2009CPOL 8.6K   1   3
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
GeneralI recommend the use of an alias: using DogCat=Dictionary&lt... Pin
PIEBALDconsult4-Jan-12 8:27
mvePIEBALDconsult4-Jan-12 8:27 
GeneralRe: Good advice. I often do this. Pin
AspDotNetDev4-Jan-12 11:32
protectorAspDotNetDev4-Jan-12 11:32 
GeneralReason for my vote of 5 it works Pin
arunkumar812715-Jul-11 2:12
arunkumar812715-Jul-11 2:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.