Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You'll get a huge variety of opinions on this one - from "use var everywhere" to "only use var with anonymous types, where you basically have to." I like <a href="http://csharpindepth.com/ViewNote.aspx?NoteID=61" rel="noreferrer">Eric Lippert's take on it</a>:</p> <blockquote> <p>All code is an abstraction. Is what the code is “really” doing is manipulating data? No. Numbers? Bits? No. Voltages? No. Electrons? Yes, but understanding the code at the level of electrons is a bad idea! The art of coding is figuring out what the right level of abstraction is for the audience.</p> <p>In a high level language there is always this tension between WHAT the code does (semantically) and HOW the code accomplishes it. Maintenance programmers need to understand both the what and the how if they’re going to be successful in making changes.</p> <p>The whole point of LINQ is that it massively de-emphasizes the "how" and massively emphasizes the "what". By using a query comprehension, the programmer is saying to the future audience "I believe that you should neither know nor care exactly how this result set is being computed, but you should care very much about what the semantics of the resulting set are." They make the code closer to the business process being implemented and farther from the bits and electrons that make it go.</p> <p>Implicitly typed locals are just one small way in which you can deemphasize the how and thereby emphasize the what. Whether that is the right thing to do in a particular case is a judgment call. So I tell people that if knowledge of the type is relevant and its choice is crucial to the continued operation of the method, then do not use implicit typing. Explicit typing says "I am telling you how this works for a reason, pay attention". Implicit typing says "it doesn’t matter a bit whether this thing is a List or a Customer[], what matters is that it is a collection of customers."</p> </blockquote> <p>Personally I don't <em>tend</em> to use it if the type isn't reasonably obvious - where I include LINQ queries as being "reasonably obvious". I wouldn't do it for <code>Directory.GetFiles</code> for instance, as it's not really obvious that that returns a <code>string[]</code> instead of (say) a <code>FileInfo[]</code> (or something else entirely) - and that makes a big difference to what you do later.</p> <p>If there's a constructor call on the right hand side of the assignment operator, I'm much more likely to go with <code>var</code>: it's blatantly obvious what the type will be. This is particularly handy with complex generic types, e.g. <code>Dictionary&lt;string,List&lt;int&gt;&gt;</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload