Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's no extra IL code for the <code>var</code> keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.</p> <p>The only trick is that <code>var</code> will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.</p> <hr> <h3>Update 8 Years Later</h3> <p>I need to update this as my understanding has changed. I now believe it may be possible for <code>var</code> to affect performance in the situation where a method returns an interface, but you would have used an exact type. For example, if you have this method:</p> <pre><code>IList&lt;int&gt; Foo() { return Enumerable.Range(0,10).ToList(); } </code></pre> <p>Consider these three lines of code to call the method: </p> <pre><code>List&lt;int&gt; bar1 = Foo(); IList&lt;int&gt; bar = Foo(); var bar3 = Foo(); </code></pre> <p>All three compile and execute as expected. However, the first two lines are <em>not</em> exactly the same, and the third line will match the second, rather than the first. Because the signature of <code>Foo()</code> is to return an <code>IList&lt;int&gt;</code>, that is how the compiler will build the <code>bar3</code> variable.</p> <p>From a performance standpoint, mostly you won't notice. However, there are situations where <a href="https://stackoverflow.com/questions/7225205/performance-of-direct-virtual-call-vs-interface-call-in-c-sharp">the performance of the third line may not be quite as fast as the performance of the first</a>. As you continue to use the <code>bar3</code> variable, the compiler may not be able to dispatch method calls the same way. </p> <p>Note that it's possible (likely even) the jitter will be able to erase this difference, but it's not guaranteed. <strong>Generally, you should still consider <code>var</code> to be a non-factor in terms of performance.</strong> It's certainly not at all like using a <code>dynamic</code> variable. But to say it never makes a difference at all may be overstating it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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