Note that there are some explanatory texts on larger screens.

plurals
  1. POUse of var keyword in C#
    text
    copied!<p>After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?</p> <p>For example I rather lazily used var in questionable circumstances, e.g.:-</p> <pre><code>foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. </code></pre> <p>More legitimate uses of var are as follows:-</p> <pre><code>var l = new List&lt;string&gt;(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. </code></pre> <p>Interestingly LINQ seems to be a bit of a grey area, e.g.:-</p> <pre><code>var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. </code></pre> <p>It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.</p> <p>It's even worse when it comes to LINQ to objects, e.g.:-</p> <pre><code>var results = from item in someList where item != 3 select item; </code></pre> <p>This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.</p> <p>There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable&lt;int&gt; and IEnumerable&lt;double&gt; the caller might inadvertently pass in the wrong type.</p> <p><code>var</code> <em>does</em> maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.</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