Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>var</code> is a <a href="http://msdn.microsoft.com/en-us/library/the35c6y.aspx" rel="nofollow noreferrer"><em>contextual keyword</em></a> - along with <code>yield</code>, <code>add</code> and <code>get</code> for example.</p> <p>In other words, you can use it as an identifer without prefixing it with @, but it still has a special meaning to the compiler in some places (i.e. where a type name is expected for a local variable declaration).</p> <p>Using <code>var</code> to declare a local variable asks the compiler to <em>infer</em> the type of the variable based on the expression on the right hand side. For example:</p> <pre><code>var list = new List&lt;string&gt;(); var anon = new { Foo = "bar" }; </code></pre> <p>The type of <code>list</code> is <code>List&lt;string&gt;</code>; the type of <code>anon</code> is an <em>anonymous type</em>, also introduced in C# 3. Part of the reason for introducing <code>var</code> in C# 3 was to allow for strongly typed variables using anonymous types - the variable still has the appropriate compile-time type, even though you couldn't explicitly state that type.</p> <p>There are a few cases where <code>var</code> doesn't work, however, if the compiler doesn't have enough information:</p> <pre><code>var cantUseNull = null; var cantUseLambda = x =&gt; x.Length; </code></pre> <p>There are others too. In each case you <em>could</em> just cast the expression on the right-hand side, so that the compiler knew what to use - but in that case you might as well just declare the variable explicitly instead.</p> <p><code>&lt;plug&gt;</code><br> You can read more about this in <a href="http://manning.com/skeet2" rel="nofollow noreferrer">C# in Depth</a>. Fortunately, the chapter covering this is still available for free from the <a href="http://manning.com/skeet" rel="nofollow noreferrer">first edition page</a> (you want chapter 8). I can't remember how much I've changed this chapter in the second edition...<br> <code>&lt;/plug&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