<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>

[{'answer_id': 41486, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 6, 'selected': False, 'text': '<p>I think the use of var should be coupled with wisely-chosen variable names.</p>\n\n<p>I have no problem using var in a foreach statement, provided it\'s not like this:</p>\n\n<pre><code>foreach (var c in list) { ... }\n</code></pre>\n\n<p>If it were more like this:</p>\n\n<pre><code>foreach (var customer in list) { ... }\n</code></pre>\n\n<p>... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that\'s even better.</p>\n\n<p>The same can apply to other situations. This is pretty useless:</p>\n\n<pre><code>var x = SaveFoo(foo);\n</code></pre>\n\n<p>... but this makes sense:</p>\n\n<pre><code>var saveSucceeded = SaveFoo(foo);\n</code></pre>\n\n<p>Each to his own, I guess. I\'ve found myself doing this, which is just insane:</p>\n\n<pre><code>var f = (float)3;\n</code></pre>\n\n<p>I need some sort of 12-step var program. My name is Matt, and I (ab)use var.</p>\n'}, {'answer_id': 41487, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 1, 'selected': False, 'text': '<p>In our office, our CTO has categorically banned the use of the var keyword, for the same reasons that you have stated.</p>\n\n<p>Personally I find the use of var only valid in new object declarations, since the type of the object is obvious in the statement itself.</p>\n\n<p>For LINQ queries, you can resolve results to:</p>\n\n<pre><code>IEnumerable&lt;TypeReturnedBySelectObject&gt;\n</code></pre>\n'}, {'answer_id': 41488, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>I had the same concern when I started to use <em>var</em> keyword.<br>\nHowever I got used to it over time and not going to go back to explicit variable types. \nVisual Studio\'s compiler\\intellisense are doing a very good job on making work with implicitly typed variables much easier. </p>\n\n<p>I think that following proper naming conventions can help you to understand code much better then explicit typing.</p>\n\n<p>It seems to be same sort of questions like "shoud I use prefixes in variable names?".<br>\nStick with good variable names and let the compiler think on variable types.</p>\n'}, {'answer_id': 41496, 'author': 'erlando', 'author_id': 4192, 'author_profile': 'https://Stackoverflow.com/users/4192', 'pm_score': 2, 'selected': False, 'text': "<p>Someone doesn't like criticism of var.. All answers downmodded.. oh well..</p>\n\n<p>@Jon Limjap:\nI know. :) What I meant was that the readability is degraded like it is in VB6. I don't like to rely on Intellisense to figure out what type a given variable is. I want to be able to figure it out using the source alone.</p>\n\n<p>Naming conventions doesn't help either - I already use good names. Are we going back to prefixing?</p>\n"}, {'answer_id': 41501, 'author': 'Murph', 'author_id': 1070, 'author_profile': 'https://Stackoverflow.com/users/1070', 'pm_score': 3, 'selected': False, 'text': "<p>I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases). </p>\n\n<p>If you've <em>got</em> a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).</p>\n\n<p>A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.</p>\n\n<p>The other thing to remember is that its not a VB type var in that it can't change types - it <strong>is</strong> a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).</p>\n\n<p>I suspect this one is going to run and run (-:</p>\n\n<p>Murph</p>\n"}, {'answer_id': 41503, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 4, 'selected': False, 'text': "<p>One specific case where var is difficult: offline code reviews, especially the ones done on paper.</p>\n\n<p>You can't rely on mouse-overs for that.</p>\n"}, {'answer_id': 41505, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 9, 'selected': True, 'text': "<p>I still think <code>var</code> can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:</p>\n\n<pre><code>var orders = cust.Orders;\n</code></pre>\n\n<p>I don't care if Customer.Orders is <code>IEnumerable&lt;Order&gt;</code>, <code>ObservableCollection&lt;Order&gt;</code> or <code>BindingList&lt;Order&gt;</code> - all I want is to keep that list in memory to iterate over it or get its count or something later on.</p>\n\n<p>Contrast the above declaration with:</p>\n\n<pre><code>ObservableCollection&lt;Order&gt; orders = cust.Orders;\n</code></pre>\n\n<p>To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from <code>ObservableCollection&lt;Order&gt;</code> to <code>IList&lt;Order&gt;</code>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.</p>\n"}, {'answer_id': 41507, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': "<p>@erlando, out of curiosity, why do you need to know the variable's type looking at the source code? </p>\n\n<p>In my practice I found that variable type is matter for me only at the time I'm using it in the code.  </p>\n\n<p>If I'm trying to do some inappropriate operation on <em>someVar</em> compiler gladly gives me an error\\warning.</p>\n\n<p>I really don't care what type <em>someVar</em> has if I understand <em>why</em> it's being used it the given context.</p>\n"}, {'answer_id': 41514, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': False, 'text': '<p>I use <code>var</code> extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.</p>\n\n<p>Admittedly, it may mean that it\'s not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically <em>not</em> interested in the type a variable has. <code>var</code> takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn\'t actually be interested in the type of the variable but rather in what a variable <em>does</em>. This is why Microsoft also calls type inference “duck typing.”</p>\n\n<p>So, what does a variable do when I declare it using <code>var</code>? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.</p>\n\n<p>If I am using a <code>var</code> declared variable and get confused what the variable is there for, there\'s something fundamentally wrong with my code. <code>var</code> is not the cause, it only makes the symptoms visible. Don\'t blame the messenger.</p>\n\n<p>Now, the C# team has released a coding guideline stating that <code>var</code> should <em>only</em> be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to <code>var</code>). Well, screw that. As long as the C# team doesn\'t give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it\'s pure baloney. (Sorry; I\'ve got no link to the guideline in question.)</p>\n\n<p>Actually, there are some (superficially) <a href="http://www.devx.com/codemag/Article/37010/0/page/2" rel="noreferrer">good explanations</a> on why you shouldn\'t use <code>var</code> but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that <code>var</code> makes it hard to search for places where <code>MyType</code> is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).</p>\n'}, {'answer_id': 41516, 'author': 'erlando', 'author_id': 4192, 'author_profile': 'https://Stackoverflow.com/users/4192', 'pm_score': 3, 'selected': False, 'text': "<p>@aku: One example is code reviews. Another example is refactoring scenarios.</p>\n\n<p>Basically I don't want to go type-hunting with my mouse. It might not be available.</p>\n"}, {'answer_id': 41519, 'author': 'Frep D-Oronge', 'author_id': 3024, 'author_profile': 'https://Stackoverflow.com/users/3024', 'pm_score': 4, 'selected': False, 'text': '<p>I don\'t see what the big deal is..</p>\n\n<pre><code>var something = someMethod(); // Type of \'something\' not clear &lt;-- not to the compiler!\n</code></pre>\n\n<p>You still have full intellisense on \'something\', and for any ambiguous case you have your unit tests, right? ( do you? )</p>\n\n<p>It\'s not varchar, it\'s not dim, and it\'s certainly not dynamic or weak typing. It is stopping maddnes like this:</p>\n\n<pre><code>List&lt;somethinglongtypename&gt; v = new List&lt;somethinglongtypename&gt;();\n</code></pre>\n\n<p>and reducing that total mindclutter to:</p>\n\n<pre><code>var v = new List&lt;somethinglongtypename&gt;();\n</code></pre>\n\n<p>Nice, not quite as nice as:</p>\n\n<pre><code>v = List&lt;somethinglongtypename&gt;();\n</code></pre>\n\n<p>But then that\'s what <a href="http://www.google.co.uk/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fboo.codehaus.org%2F&amp;ei=XH2-SMO4B4iO1wbX1-Vf&amp;usg=AFQjCNGs4DK8A1ZnEgL7s8pcGjlMMmDOFg&amp;sig2=X0tf_m1xNuEdJ_UetIC19A" rel="nofollow noreferrer">Boo</a> is for.</p>\n'}, {'answer_id': 41520, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 0, 'selected': False, 'text': "<p>@erlando,</p>\n\n<p>Talking about refactoring it seems to be much easier to change variable type by assigning instance of new type to one variable rather then changing it in multiple places, isn't it ?</p>\n\n<p>As for code review I see no big issues with <em>var</em> keyword. During code review I prefer to check code logic rather variable types. Of course there might be scenarios where developer can use inappropriate type but I think that number of such cases is so small it wouldn't be a reason for my to stop using <em>var</em> keyword.</p>\n\n<p>So I repeat my question. <em>Why</em> does variable type matter to you?</p>\n"}, {'answer_id': 41523, 'author': 'Daren Thomas', 'author_id': 2260, 'author_profile': 'https://Stackoverflow.com/users/2260', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s a matter of taste. All this fussing about the <em>type</em> of a variable disappears when you get used to dynamically typed languages. That is, <em>if</em> you ever start to like them (I\'m not sure if everybody can, but I do).</p>\n\n<p>C#\'s <code>var</code> is pretty cool in that it <em>looks</em> like dynamic typing, but actually is <strong>static</strong> typing - the compiler enforces correct usage.</p>\n\n<p>The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don\'t expect <em>customerList</em> to contain an <code>int</code>...</p>\n\n<p>I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?</p>\n'}, {'answer_id': 41531, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': "<p>In your comparison between <code>IEnumerable&lt;int&gt;</code> and <code>IEnumerable&lt;double&gt;</code> you don't need to worry - if you pass the wrong type your code won't compile anyway.</p>\n\n<p>There's no concern about type-safety, as <code>var</code> is <strong>not</strong> dynamic. It's just compiler magic and any type unsafe calls you make will get caught. </p>\n\n<p><code>Var</code> is absolutely needed for Linq:</p>\n\n<pre><code>var anonEnumeration =\n    from post in AllPosts()\n    where post.Date &gt; oldDate\n    let author = GetAuthor( post.AuthorId )\n    select new { \n        PostName = post.Name, \n        post.Date, \n        AuthorName = author.Name\n    };\n</code></pre>\n\n<p>Now look at <em>anonEnumeration</em> in intellisense and it will appear something like <code>IEnumerable&lt;'a&gt;</code></p>\n\n<pre><code>foreach( var item in anonEnumeration ) \n{\n    //VS knows the type\n    item.PostName; //you'll get intellisense here\n\n    //you still have type safety\n    item.ItemId;   //will throw a compiler exception\n}\n</code></pre>\n\n<p>The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.</p>\n\n<p>Outside of that, as long as you have intellisense it makes good sense to use <code>var</code> anywhere the context is clear.</p>\n\n<pre><code>//less typing, this is good\nvar myList = new List&lt;UnreasonablyLongClassName&gt;();\n\n//also good - I can't be mistaken on type\nvar anotherList = GetAllOfSomeItem();\n\n//but not here - probably best to leave single value types declared\nvar decimalNum = 123.456m;\n</code></pre>\n"}, {'answer_id': 41532, 'author': 'robi-y', 'author_id': 4388, 'author_profile': 'https://Stackoverflow.com/users/4388', 'pm_score': 3, 'selected': False, 'text': '<p>I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer <code>int i = 3;</code> over <code>var i = 3;</code></p>\n'}, {'answer_id': 41634, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 0, 'selected': False, 'text': "<p>@Keith - </p>\n\n<blockquote>\n  <p>In your comparison between\n  IEnumerable&lt;int&gt; and\n  IEnumerable&lt;double&gt; you don't need to\n  worry - if you pass the wrong type\n  your code won't compile anyway.</p>\n</blockquote>\n\n<p>That isn't quite true - if a method is overloaded to both IEnumerable&lt;int&gt; and IEnumerable&lt;double&gt; then it may silently pass the unexpected inferred type (due to some other change in the program) to the wrong overload hence causing incorrect behaviour.</p>\n\n<p>I suppose the question is how likely it is that this sort of situation will come up!</p>\n\n<p>I guess part of the problem is how much confusion var adds to a given declaration - if it's not clear what type something is (despite being strongly typed and the compiler understanding entirely what type it is) someone might gloss over a type safety error, or at least take longer to understand a piece of code.</p>\n"}, {'answer_id': 41689, 'author': 'Giovanni Galbo', 'author_id': 4050, 'author_profile': 'https://Stackoverflow.com/users/4050', 'pm_score': 1, 'selected': False, 'text': "<p>I use var in the following situations:</p>\n\n<ol>\n<li>When I have to (result is anonymous)</li>\n<li><p>When the type is on the same line as the code, e.g.</p>\n\n<p>var emp = new Employee();</p></li>\n</ol>\n\n<p>Its obvious we want an Employee (because we're creating a new Employee object), so how is </p>\n\n<pre><code>Employee emp = new Employee() any more obvious?\n</code></pre>\n\n<p>I do NOT use var when the type cannot be inferred, e.g.</p>\n\n<pre><code>var emp = GetEmployee();\n</code></pre>\n\n<p>Because the return type is not immediately obvious (is at an Employee, an IEmployee, something that has nothing to do with an Employee object at all, etc?).</p>\n"}, {'answer_id': 41695, 'author': 'Pat', 'author_id': 36, 'author_profile': 'https://Stackoverflow.com/users/36', 'pm_score': 2, 'selected': False, 'text': '<p>After just converting over to the 3.0 and 3.5 frameworks I learned about this keyword and decided to give it a whirl. Before committing any code I had the realization that it seemed backwards, as in going back toward an ASP syntax. So I decided to poke the higher ups to see what they thought. </p>\n\n<p>They said go ahead so I use it.</p>\n\n<p>With that said I avoid using it where the type requires some investigation, like this:</p>\n\n<p>var a = company.GetRecords();</p>\n\n<p>Now it could just be a personal thing but I immediately cant look at that and determine if its a collection of Record objects or a string array representing the name of records. Whichever the case I believe explicit declaration is useful in such an instance.</p>\n'}, {'answer_id': 41981, 'author': 'Kevin Berridge', 'author_id': 4407, 'author_profile': 'https://Stackoverflow.com/users/4407', 'pm_score': 1, 'selected': False, 'text': '<p>I have to agree with <a href="https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c#41486">Matt Hamilton</a>.</p>\n\n<p>Var can make your code much more readable and understandable when used with good variable names.  But var can also make your code as impossible to read and understand as Perl when used badly.  </p>\n\n<p>A list of good and bad uses of var isn\'t really going to help much either.  This is a case for common sense.  The larger question is one of readability vs. write-ability.  Lots of devs don\'t care if their code is readable.  They just don\'t want to type as much.  Personally I\'m a read > write guy.</p>\n'}, {'answer_id': 43621, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 1, 'selected': False, 'text': "<p>kronoz - in that case (overloads for both) would it matter? If you have two overloads that took the different types you would essentially be saying that either can be passed and do the same thing.</p>\n\n<p>You shouldn't have two overloads that do completely different actions depending on the types passed.</p>\n\n<p>While you might get some confusion in that instance it would still be entirely type safe, you'd just have someone calling the wrong method.</p>\n"}, {'answer_id': 51785, 'author': 'Tundey', 'author_id': 1453, 'author_profile': 'https://Stackoverflow.com/users/1453', 'pm_score': 1, 'selected': False, 'text': "<p>I don't understand why people start debates like this. It really serves no purpose than to start flame wars at then end of which nothing is gained. Now if the C# team was trying to phase out one style in favor of the other, I can see the reason to argue over the merits of each style. But since both are going to remain in the language, why not use the one <em>you</em> prefer and let everybody do the same. It's like the use of everybody's favorite ternary operator: some like it and some don't. At the end of the day, it makes no difference to the compiler.</p>\n\n<p>This is like arguing with your siblings over which is your favorite parent: it doesn't matter unless they are divorcing!</p>\n"}, {'answer_id': 55642, 'author': 'nedruod', 'author_id': 5504, 'author_profile': 'https://Stackoverflow.com/users/5504', 'pm_score': 2, 'selected': False, 'text': '<p>Static typing is about contracts, not source code.  The idea there is a need to have the static information on a single line of what "should" be a small method.  Common guidelines recommend rarely exceeding 25 lines per method.</p>\n\n<p>If a method is large enough that you can\'t keep track of a single variable within that method, you are doing something else wrong that would make any criticism of var pale in comparison.</p>\n\n<p>Actually, one of the great arguments for var is that it can make refactoring simpler because you no longer have to worry that you made your declaration overly restrictive (i.e. you used List&lt;> when you should have used IList&lt;>, or IEnumerable&lt;>).  You still want to think about the new methods signature, but at least you won\'t have to go back and change your declarations to match.</p>\n'}, {'answer_id': 67083, 'author': 'AlanR', 'author_id': 7311, 'author_profile': 'https://Stackoverflow.com/users/7311', 'pm_score': 1, 'selected': False, 'text': "<p>I find that using the var keyword actually makes the code more readable because you just get used to skipping the 'var' keyword.  You don't need to keep scrolling right to figure out what the code is doing when you really don't care about what the specific type is.  If I really need to know what type 'item' is below, I just hover my mouse over it and Visual Studio will tell me.  In other words, I would much rather read</p>\n\n<pre><code>foreach( var item in list ) { DoWork( item ); }\n</code></pre>\n\n<p>over and over than</p>\n\n<pre><code>foreach( KeyValuePair&lt;string, double&gt; entry in list ) { DoWork( Item ); }\n</code></pre>\n\n<p>when I am trying to digest the code.  I think it boils down to personal preference to some extent.  I would rely on common sense on this one -- save enforcing standards for the important stuff (security, database use, logging, etc.)</p>\n\n<p>-Alan.</p>\n"}, {'answer_id': 78833, 'author': 'Dexter', 'author_id': 10717, 'author_profile': 'https://Stackoverflow.com/users/10717', 'pm_score': 5, 'selected': False, 'text': '<p>We\'ve adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.</p>\n\n<p>For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can\'t write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.</p>\n\n<p>Thus,</p>\n\n<pre><code>var something = SomeMethod();\n</code></pre>\n\n<p>is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:</p>\n\n<pre><code>var list = new List&lt;KeyValuePair&lt;string, double&gt;&gt;();\nFillList( list );\nforeach( var item in list ) {\n   DoWork( item ); \n}\n</code></pre>\n'}, {'answer_id': 96490, 'author': 'Dustman', 'author_id': 16398, 'author_profile': 'https://Stackoverflow.com/users/16398', 'pm_score': 6, 'selected': False, 'text': '<p>From Eric Lippert, a Senior Software Design Engineer on the C# team:</p>\n\n<p>Why was the <code>var</code> keyword introduced?</p>\n\n<blockquote>\n  <p>There are two reasons, one which\n  exists today, one which will crop up\n  in 3.0.</p>\n  \n  <p>The first reason is that this code is\n  incredibly ugly because of all the\n  redundancy:</p>\n  \n  <p><code>Dictionary&lt;string, List&lt;int&gt;&gt; mylists = new Dictionary&lt;string, List&lt;int&gt;&gt;();</code></p>\n  \n  <p>And that\'s a simple example – I\'ve\n  written worse. Any time you\'re forced\n  to type exactly the same thing twice,\n  that\'s a redundancy that we can\n  remove. Much nicer to write</p>\n  \n  <p><code>var mylists = new Dictionary&lt;string,List&lt;int&gt;&gt;();</code></p>\n  \n  <p>and let the compiler figure out what\n  the type is based on the assignment.</p>\n  \n  <p>Second, C# 3.0 introduces anonymous\n  types. Since anonymous types by\n  definition have no names, you <strong>need</strong> to\n  be able to infer the type of the\n  variable from the initializing\n  expression if its type is anonymous.</p>\n</blockquote>\n\n<p>Emphasis mine. The whole article, <a href="http://blogs.msdn.com/ericlippert/archive/2005/09/27/c-3-0-is-still-statically-typed-honest.aspx" rel="noreferrer">C# 3.0 is still statically typed, honest!</a>, and the ensuing <a href="http://blogs.msdn.com/ericlippert/archive/tags/Type+Inference/default.aspx" rel="noreferrer">series</a> are pretty good.</p>\n\n<p>This is what <code>var</code> is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, <code>var</code> is <strong>required</strong> in order to have certain other features work in .NET.</p>\n'}, {'answer_id': 105485, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 3, 'selected': False, 'text': "<p>To me, the antipathy towards <code>var</code> illustrates why bilingualism in .NET is important.  To those C# programmers who have also done VB .NET, the advantages of <code>var</code> are intuitively obvious.  The standard C# declaration of:</p>\n\n<pre><code>List&lt;string&gt; whatever = new List&lt;string&gt;();\n</code></pre>\n\n<p>is the equivalent, in VB .NET, of typing this:</p>\n\n<pre><code>Dim whatever As List(Of String) = New List(Of String)\n</code></pre>\n\n<p>Nobody does that in VB .NET, though.  It would be silly to, because since the first version of .NET you've been able to do this...</p>\n\n<pre><code>Dim whatever As New List(Of String)\n</code></pre>\n\n<p>...which creates the variable and initializes it all in one reasonably compact line.  Ah, but what if you want an <code>IList&lt;string&gt;</code>, not a <code>List&lt;string&gt;</code>?  Well, in VB .NET that means you have to do this:</p>\n\n<pre><code>Dim whatever As IList(Of String) = New List(Of String)\n</code></pre>\n\n<p>Just like you'd have to do in C#, and obviously couldn't use <code>var</code> for:</p>\n\n<pre><code>IList&lt;string&gt; whatever = new List&lt;string&gt;();\n</code></pre>\n\n<p>If you <em>need</em> the type to be something different, it can be.  But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.</p>\n"}, {'answer_id': 133732, 'author': 'Neil Hewitt', 'author_id': 22178, 'author_profile': 'https://Stackoverflow.com/users/22178', 'pm_score': 3, 'selected': False, 'text': "<p>Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using <code>var</code> for any old declaration makes me do that all the time, which I personally find uncomfortable.</p>\n\n<p>Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole '<code>var</code> or not' thing into the mix. The worst case will be where one programmer didn't use <code>var</code> and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess. </p>\n\n<p>Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a <strong>big</strong> difference.</p>\n\n<p>I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.</p>\n"}, {'answer_id': 213704, 'author': 'TimothyP', 'author_id': 28149, 'author_profile': 'https://Stackoverflow.com/users/28149', 'pm_score': 1, 'selected': False, 'text': '<p>I think people do not understand the var keyword.\nThey confuse it with the Visual Basic / JavaScript keyword,\nwhich is a different beast all toghether.</p>\n\n<p>Many people think the var keyword implies\nweak typing (or dynamic typing), while in fact c# is and remains strongly typed.</p>\n\n<p>If you consider this in javascript:</p>\n\n<pre><code>var something = 5;\n</code></pre>\n\n<p>you are allowed to:</p>\n\n<pre><code>something = "hello";\n</code></pre>\n\n<p>In the case of c#, the compiler would infer the type from the first statement,\ncausing something to be of type "int", so the second statement would result\nin an exception.</p>\n\n<p>People simply need to understand that using the var keyword does not imply\ndynamic typing and then decide how far they want to take the use of the var keyword,\nknowing it will have absolutely no difference as to what will be compiled.</p>\n\n<p>Sure the var keyword was introduced to support anonymous types,\nbut if you look at this:</p>\n\n<pre><code>LedDeviceController controller = new LedDeviceController("172.17.0.1");\n</code></pre>\n\n<p>It\'s very very verbose, and I\'m sure this is just as readable, if not more:</p>\n\n<pre><code>var controller = new LedDeviceController("172.17.0.1");\n</code></pre>\n\n<p>The result is exactly the same, so yes I use it throughout my code</p>\n\n<p>UPDATE:</p>\n\n<p>Maybe, just maybe... they should have used another keyword,\nthen we would not be having this discussion... perhaps the "infered" keyword instead of "var"</p>\n'}, {'answer_id': 321277, 'author': 'Richard Ev', 'author_id': 39709, 'author_profile': 'https://Stackoverflow.com/users/39709', 'pm_score': 0, 'selected': False, 'text': '<p><code>var</code> is essential for anonymous types (as pointed out in one of the previous responses to this question).</p>\n\n<p>I would categorise all other discussion of its pros and cons as "religious war". By that I mean that a comparison and discussion of the relative merits of...</p>\n\n<pre><code>var i = 5;\nint j = 5;\n\nSomeType someType = new SomeType();\nvar someType = new SomeType();\n</code></pre>\n\n<p>...is entirely subjective.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/bb384061.aspx" rel="nofollow noreferrer">Implicit typing</a> means that there is no runtime penalty for any variable being declared using the <code>var</code> keyword, so it comes down to being a debate about what makes the developers happy. </p>\n'}, {'answer_id': 391590, 'author': 'Rostov', 'author_id': 2108310, 'author_profile': 'https://Stackoverflow.com/users/2108310', 'pm_score': 3, 'selected': False, 'text': '<p>Stolen from the <a href="http://www.codinghorror.com/blog/archives/001136.html" rel="nofollow noreferrer">post on this issue at CodingHorror</a>:</p>\n\n<hr>\n\n<p><em>Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:</p>\n\n<p>MyObject m = new();</p>\n\n<p>Or if you are passing parameters:</p>\n\n<p>Person p = new("FirstName", "LastName);</p>\n\n<p>Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won\'t get into it here).</p>\n\n<p>In the end, it just wasn\'t intended to reduce redundancy. Don\'t get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I\'ve been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.</p>\n\n<p>Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM</em></p>\n\n<hr>\n\n<p>I guess if your main concern is to have to type less -- then there isn\'t any argument that\'s going to sway you from using it.</p>\n\n<p>If you are only going to <strong>ever</strong> be the person who looks at your code, then who cares?  Otherwise, in a case like this:</p>\n\n<pre><code>var people = Managers.People\n</code></pre>\n\n<p>it\'s fine, but in a case like this:</p>\n\n<pre><code>var fc = Factory.Run();\n</code></pre>\n\n<p>it short circuits any immediate type deductions my brain could begin forming from the \'English\' of the code.</p>\n\n<p>Otherwise, just use your best judgment and programming \'courtesy\' towards others who might have to work on your project.</p>\n'}, {'answer_id': 488436, 'author': 'Christian Klauser', 'author_id': 55208, 'author_profile': 'https://Stackoverflow.com/users/55208', 'pm_score': 2, 'selected': False, 'text': "<p>I use <code>var</code> whenever possible. </p>\n\n<p>The actual type of the local variable <em>shouldn't matter</em> if your code is well written (i.e., good variable names, comments, clear structure etc.)</p>\n"}, {'answer_id': 498706, 'author': 'Chris S', 'author_id': 21574, 'author_profile': 'https://Stackoverflow.com/users/21574', 'pm_score': 0, 'selected': False, 'text': "<p>I don't use var as it goes against the roots of C# - C/C++/Java. Even though it's a compiler trick it makes the language feel like it's less strongly typed. Maybe 20+ years of C have engrained it all into our (the anti-var people's) heads that we should have the type on both the left and right side of the equals.</p>\n\n<p>Having said that I can see its merits for long generic collection definitions and long class names like the codinghorror.com example, but elsewhere such as string/int/bool I really can't see the point. Particularly</p>\n\n<pre><code>foreach (var s in stringArray)\n{\n\n}\n</code></pre>\n\n<p>a saving of 3 characters!</p>\n\n<p>The main annoyance for me is not being able to see the type that the var represents for method calls, unless you hover over the method or F12 it.</p>\n"}, {'answer_id': 537411, 'author': 'user37468', 'author_id': 37468, 'author_profile': 'https://Stackoverflow.com/users/37468', 'pm_score': 0, 'selected': False, 'text': '<p>VS2008 w/resharper 4.1 has correct typing in the tooltip when you hover over "var" so I think it should be able to find this when you look for all usages of a class.</p>\n\n<p>Haven\'t yet tested that it does that yet though.</p>\n'}, {'answer_id': 792765, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 1, 'selected': False, 'text': '<p>Arriving a bit late at this discussion, but I\'d just like to add a thought.</p>\n\n<p>To all those who are against type inference (because that\'s what we\'re really talking about here), what about lambda expressions? If you insist on always declaring types explicitly (except for anonymous types), what do you do with lambdas? How does the "Don\'t make me use mouseover" argument apply to var but not to lambdas?</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I\'ve just thought of one argument against \'var\' which I don\'t think anyone has mentioned yet, which is that it \'breaks\' "Find all references", which could mean (for example) that if you were checking out usage of a class before refactoring, you would miss all the place where the class was used via <code>var</code>.</p>\n'}, {'answer_id': 971916, 'author': 'Colin', 'author_id': 119660, 'author_profile': 'https://Stackoverflow.com/users/119660', 'pm_score': 0, 'selected': False, 'text': "<p>Depends, somehow it makes the code look 'cleaner', but agree it makes it more unreadable to...</p>\n"}, {'answer_id': 971919, 'author': 'mqp', 'author_id': 55943, 'author_profile': 'https://Stackoverflow.com/users/55943', 'pm_score': 3, 'selected': False, 'text': '<p>I guess it depends on your perspective.  I personally have never had any difficulty understanding a piece of code because of <code>var</code> "misuse", and my coworkers and I use it quite a lot all over.  (I agree that Intellisense is a huge aid in this regard.)  I welcome it as a way to remove repetitive cruft.</p>\n\n<p>After all, if statements like</p>\n\n<pre><code>var index = 5; // this is supposed to be bad\n\nvar firstEligibleObject = FetchSomething(); // oh no what type is it\n                                            // i am going to die if i don\'t know\n</code></pre>\n\n<p>were really that impossible to deal with, nobody would use dynamically typed languages.</p>\n'}, {'answer_id': 971930, 'author': 'SLaks', 'author_id': 34397, 'author_profile': 'https://Stackoverflow.com/users/34397', 'pm_score': 0, 'selected': False, 'text': '<p>It can make code simpler and shorter, especially with complicated generic types and delegates.</p>\n\n<p>Also, it makes variable types easier to change.</p>\n'}, {'answer_id': 971934, 'author': 'Colin Desmond', 'author_id': 93399, 'author_profile': 'https://Stackoverflow.com/users/93399', 'pm_score': 4, 'selected': False, 'text': '<p>Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area. </p>\n\n<p>If you have a line of code such as </p>\n\n<pre><code>IDictionary&lt;BigClassName, SomeOtherBigClassName&gt; nameDictionary = new Dictionary&lt;BigClassName, SomeOtherBigClassName&gt;();\n</code></pre>\n\n<p>Is is much easier or harder to read than:</p>\n\n<pre><code>var nameDictionary = new Dictionary&lt;BigClassName, SomeOtherBigClassName&gt;();\n</code></pre>\n'}, {'answer_id': 971943, 'author': 'Jeff Yates', 'author_id': 23234, 'author_profile': 'https://Stackoverflow.com/users/23234', 'pm_score': 0, 'selected': False, 'text': "<p><code>var</code> is great when you don't want to repeat yourself. For example, I needed a data structure yesterday that was similar to this. Which representation do you prefer?</p>\n\n<pre><code>Dictionary&lt;string, Dictionary&lt;string, List&lt;MyNewType&gt;&gt;&gt; collection = new Dictionary&lt;string, Dictionary&lt;string, List&lt;MyNewType&gt;&gt;&gt;();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var collection = new Dictionary&lt;string, Dictionary&lt;string, List&lt;MyNewType&gt;&gt;&gt;();\n</code></pre>\n\n<p>Note that there is little ambiguity introduced by using <code>var</code> in this example. However, there are times when it wouldn't be such a good idea. For example, if I used <code>var</code> as in the following,</p>\n\n<pre><code>var value= 5;\n</code></pre>\n\n<p>when I could just write the real type and remove any ambiguity in how <code>5</code> should be represented.</p>\n\n<pre><code>double value = 5;\n</code></pre>\n"}, {'answer_id': 971949, 'author': 'Richard', 'author_id': 67392, 'author_profile': 'https://Stackoverflow.com/users/67392', 'pm_score': 3, 'selected': False, 'text': "<p>It can certainly make things simpler, from code I wrote yesterday:</p>\n\n<pre><code>var content  = new Queue&lt;Pair&lt;Regex, Func&lt;string, bool&gt;&gt;&gt;();\n...\nforeach (var entry in content) { ... }\n</code></pre>\n\n<p>This would have be extremely verbose without <code>var</code>.</p>\n\n<p>Addendum: A little time spent with a language with <em>real</em> type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use <code>var</code> as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.</p>\n"}, {'answer_id': 971967, 'author': 'BFree', 'author_id': 15861, 'author_profile': 'https://Stackoverflow.com/users/15861', 'pm_score': 3, 'selected': False, 'text': "<p>Many time during testing, I find myself having code like this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\nConsole.WriteLine(something);\n</code></pre>\n\n<p>Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing;\n</code></pre>\n\n<p>Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.</p>\n"}, {'answer_id': 971997, 'author': 'Serapth', 'author_id': 101767, 'author_profile': 'https://Stackoverflow.com/users/101767', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t think var per say is a terrible language feature, as I use it daily with code like what Jeff Yates described.  Actually, almost everytime I use var is because generics can make for some extremely wordy code.  I live verbose code but generics take it a step too far.</p>\n\n<p>That said, I (obviously... ) think var is ripe for abuse.  If code gets to 20+ lines in a method with vars littered through out, you will quickly make maintenance a nightmare.  Additionally, var in a tutorial is incredibly counter intuitive and generally is a giant no-no in my books.</p>\n\n<p>On the flipside, var is an "easy" feature that new programmers are going to latch onto and love.  Then, within a few minutes/hours/days hit a massive roadblock when they start hitting the limits.  "Why can\'t I return var from functions?"  That kind of question.  Also, adding a pseudo dynamic type to a strongly typed language is something that can easily trip up a new developer.  In the long run, I think the var keyword will actually make c# harder to learn for new programmers.</p>\n\n<p>That said, as an experienced programmer I do use var, mostly when dealing with generics ( and obviously anonymous types ). I do hold by my quote, I do believe var will be one of the worst abused c# features.</p>\n'}, {'answer_id': 972071, 'author': 'Euro Micelli', 'author_id': 2230, 'author_profile': 'https://Stackoverflow.com/users/2230', 'pm_score': 2, 'selected': False, 'text': '<p>There is bound to be disagreement near the edge cases, but I can tell you my personal guidelines.</p>\n\n<p>I look at these the criteria when I decide to use <code>var</code>:</p>\n\n<ul>\n<li>The type of the variable is <em>obvious</em> [to a human] from the context</li>\n<li>The exact type of the variable is <em>not particularly relevant</em> [to a human]<br>\n<em>[e.g. you can figure out what the algorithm is doing without caring about what kind of container you are using]</em></li>\n<li>The type name is very long and interrupts the readability of the code (<em>hint: usually a generic</em>)</li>\n</ul>\n\n<p>Conversely, these situations would push me to not use <code>var</code>:</p>\n\n<ul>\n<li>The type name is relatively short and easy to read (<em>hint: usually not a generic</em>)</li>\n<li>The type is <em>not obvious</em> from the initializer\'s name</li>\n<li>The exact type is very important to understand the code/algorithm</li>\n<li>On class hierarchies, when a human can\'t easily tell which level of the hierarchy is being used</li>\n</ul>\n\n<p>Finally, I would never use <code>var</code> for native value types or corresponding <code>nullable&lt;&gt;</code> types (<code>int</code>, <code>decimal</code>, <code>string</code>, <code>decimal?</code>, ...). There is an implicit assumption that if you use <code>var</code>, there must be "a reason".</p>\n\n<p>These are all guidelines. You should also think also about the experience and skills of your coworkers, the complexity of the algorithm, the longevity/scope of the variable, etc, etc.</p>\n\n<p>Most of the time, there is no perfect right answer. Or, it doesn\'t really matter.</p>\n\n<p><em>[Edit: removed a duplicate bullet]</em></p>\n'}, {'answer_id': 1031291, 'author': 'Jamie Eisenhart', 'author_id': 19533, 'author_profile': 'https://Stackoverflow.com/users/19533', 'pm_score': 0, 'selected': False, 'text': '<p>From <a href="https://rads.stackoverflow.com/amzn/click/com/0321564162" rel="nofollow noreferrer" rel="nofollow noreferrer">Essential LINQ</a>:</p>\n\n<p>It is best not to explicitly declare the type of a range variable unless absolutely necessary. For instance, the following code compiles cleanly, but the type could have been inferred by the compiler without a formal declaration:</p>\n\n<pre><code>List&lt;string&gt; list = new List&lt;string&gt; { "LINQ", "query", "adventure" };\nvar query = from string word in list\n      where word.Contains("r")\n      orderby word ascending\n      select word;\n</code></pre>\n\n<p>Explicitly declaring the type of a range variable forces a behind-the-scenes call to the LINQ Cast operator. This call may have unintended consequences and may hurt performance. If you encounter performance problems with a LINQ query, a cast like the one shown here is one possible place to begin looking for the culprit. (The one exception to this rule is when you are working with a nongeneric Enumerable, in which case you should use the cast.)</p>\n'}, {'answer_id': 1298234, 'author': 'Ignas R', 'author_id': 153569, 'author_profile': 'https://Stackoverflow.com/users/153569', 'pm_score': 3, 'selected': False, 'text': '<p>None, except that you don\'t have to write the type name twice. <a href="http://msdn.microsoft.com/en-us/library/bb383973.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb383973.aspx</a></p>\n'}, {'answer_id': 1298236, 'author': 'Rune FS', 'author_id': 112407, 'author_profile': 'https://Stackoverflow.com/users/112407', 'pm_score': 2, 'selected': False, 'text': "<p>It's purely a convinience. The compiler will inferre the type (based on the type of the expression on the right hand side)</p>\n"}, {'answer_id': 1298237, 'author': 'ShdNx', 'author_id': 128240, 'author_profile': 'https://Stackoverflow.com/users/128240', 'pm_score': 3, 'selected': False, 'text': '<p>In most cases, it\'s just simpler to type it - imagine</p>\n\n<pre><code>var sb = new StringBuilder();\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n</code></pre>\n\n<p>Sometimes it\'s required, for example: anonymous types, like.</p>\n\n<pre><code>var stuff = new { Name = "Me", Age = 20 };\n</code></pre>\n\n<p>I personally like using it, in spite of the fact that it makes the code less readable and maintainable.</p>\n'}, {'answer_id': 1298256, 'author': 'GONeale', 'author_id': 41211, 'author_profile': 'https://Stackoverflow.com/users/41211', 'pm_score': 0, 'selected': False, 'text': "<p>You don't have to write out the type name and no this is not less performant as the type is resolved at compile time.</p>\n"}, {'answer_id': 1298268, 'author': 'Marc Gravell', 'author_id': 23354, 'author_profile': 'https://Stackoverflow.com/users/23354', 'pm_score': 5, 'selected': False, 'text': '<p>The most likely time you\'ll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don\'t need to see the type twice for a simple initialization.</p>\n\n<p>For example:</p>\n\n<pre><code>Dictionary&lt;string, List&lt;SomeComplexType&lt;int&gt;&gt;&gt; data = new Dictionary&lt;string, List&lt;SomeComplexType&lt;int&gt;&gt;&gt;();\n</code></pre>\n\n<p>(please don\'t edit the hscroll in the above - it kinda proves the point!!!)</p>\n\n<p>vs:</p>\n\n<pre><code>var data = new Dictionary&lt;string, List&lt;SomeComplexType&lt;int&gt;&gt;&gt;();\n</code></pre>\n\n<p>There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using <code>var</code> if the original variable and initialized type weren\'t identical. For example:</p>\n\n<pre><code>static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }\nstatic void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}\n\n// this working code...\nIFoo oldCode = new Foo();\nDoSomething(oldCode);\n// ...is **very** different to this code\nvar newCode = new Foo();\nDoSomething(newCode);\n</code></pre>\n'}, {'answer_id': 1298283, 'author': 'MartinStettner', 'author_id': 81424, 'author_profile': 'https://Stackoverflow.com/users/81424', 'pm_score': 3, 'selected': False, 'text': '<p>Using <code>var</code> instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").</p>\n\n<p>You can change the return type of your methods without changing every file where this method is called. Imagine</p>\n\n<pre><code>...\nList&lt;MyClass&gt; SomeMethod() { ... }\n...\n</code></pre>\n\n<p>which is used like</p>\n\n<pre><code>...\nIList&lt;MyClass&gt; list = obj.SomeMethod();\nforeach (MyClass c in list)\n  System.Console.WriteLine(c.ToString());\n...\n</code></pre>\n\n<p>If you wanted to refactor <code>SomeMethod()</code> to return an <code>IEnumerable&lt;MySecondClass&gt;</code>, you would have to change the variable declaration (also inside the <code>foreach</code>) in every place you used the method.</p>\n\n<p>If you write</p>\n\n<pre><code>...\nvar list = obj.SomeMethod();\nforeach (var element in list)\n  System.Console.WriteLine(element.ToString());\n...\n</code></pre>\n\n<p>instead, you don\'t have to change it.</p>\n'}, {'answer_id': 1298297, 'author': 'Ira Baxter', 'author_id': 120163, 'author_profile': 'https://Stackoverflow.com/users/120163', 'pm_score': 1, 'selected': False, 'text': '<p>You can let the compiler (and the fellow who maintains the code next) infer the type from the right hand side of the initializer assignment.   If this inference is possible, the compiler can do it so it saves some typing on your part. </p>\n\n<p>If the inference is easy for that poor fellow, then you haven\'t hurt anything.  If the inference is hard, you\'ve made the code harder to maintain and so as a general rule\nI wouldn\'t do it.</p>\n\n<p>Lastly, if you intended the type to be something particular, and your initializer expression actually has a different type, using var means it will be harder for you to find the induced bug.   By explicitly telling the compiler what you intend the type to be, when the type isn\'t that, you would get an immediate diagnostic.  By sluffing on the type declaration and using "var", you won\'t get an error on the initialization; instead, you\'ll get a type error in some expression that uses the identifier assigned by the var expression, and it will be harder to understand why.</p>\n\n<p>So the moral is, use var sparingly; you generally aren\'t doing yourself or your downstream fellow maintainer a lot of good.  And hope he reasons the same way, so you aren\'t stuck guessing his intentions because <em>he</em> thought using var was easy.  Optimizing on how much you type is a mistake when coding a system with a long life.</p>\n'}, {'answer_id': 1298706, 'author': 'saret', 'author_id': 155438, 'author_profile': 'https://Stackoverflow.com/users/155438', 'pm_score': 1, 'selected': False, 'text': '<p>Sometimes the compiler can also infer what is required "better" than the developer - at least a developer who does not understand what the api he\'s using requires.</p>\n\n<p>For example - when using linq:</p>\n\n<p>Example 1</p>\n\n<pre><code>Func&lt;Person, bool&gt; predicate = (i) =&gt; i.Id &lt; 10;\nIEnumerable&lt;Person&gt; result = table.Where(predicate);\n</code></pre>\n\n<p>Example 2</p>\n\n<pre><code>var predicate = (Person i) =&gt; i.Id &lt; 10;\nvar result = table.Where(predicate);\n</code></pre>\n\n<p>In the above code - assuming one is using Linq to Nhibernate or Linq to SQL, Example 1 will\nbring the entire resultset for Person objects back and then do filter on the client end.\nExample 2 however will do the query on the server (such as on Sql Server with SQL) as the compiler is smart enough to work out that the Where function should take a Expression> rather than a Func. </p>\n\n<p>The result in Example 1 will also not be further queryable on the server as an IEnumerable is returned, while in Example 2 the compiler can work out if the result should rather be a IQueryable instead of IEnumerable</p>\n'}, {'answer_id': 1367659, 'author': 'krystan honour', 'author_id': 134848, 'author_profile': 'https://Stackoverflow.com/users/134848', 'pm_score': 3, 'selected': False, 'text': '<p>I used to think that the var keyword was a great invention but I put a a limit on it this was</p>\n\n<ul>\n<li>Only use var where it is obvious what the type is immediately (no scrolling or looking at return types)</li>\n</ul>\n\n<p>I came to realise this then gave me no benefit whatsoever and removed all var keywords from my code (unless they were specifically required), for now I think that they make the code less readable, especially to others reading your code.</p>\n\n<p>It hides intent and in at least one instance lead to a runtime bug in some code because of assumption of type.</p>\n'}, {'answer_id': 1724070, 'author': 'David_001', 'author_id': 209578, 'author_profile': 'https://Stackoverflow.com/users/209578', 'pm_score': 2, 'selected': False, 'text': '<p>From the discussion on this topic, the outcome appears to be:</p>\n\n<p>Good: <code>var customers = new List&lt;Customer&gt;();</code></p>\n\n<p>Controversial: <code>var customers = dataAccess.GetCustomers();</code></p>\n\n<p>Ignoring the misguided opinion that "var" magically helps with refactoring, the biggest issue for me is people\'s insistence that they don\'t care what the return type is, "so long as they can enumerate the collection".  </p>\n\n<p>Consider:  </p>\n\n<pre><code>IList&lt;Customer&gt; customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n</code></pre>\n\n<p>Now consider:</p>\n\n<pre><code>var customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n</code></pre>\n\n<p>Now, go and refactor the data access class, so that GetCustomers returns <code>IEnumerable&lt;Customer&gt;</code>, and see what happens...</p>\n\n<p>The problem here is that in the first example you\'re making your expectations of the GetCustomers method explicit - you\'re saying that you expect it to return something that behaves like a list. In the second example, this expectation is implicit, and not immediately obvious from the code.</p>\n\n<p>It\'s interesting (to me) that a lot of pro-var arguments say "i don\'t care what type it returns", but go on to say "i just need to iterate over it...".  (so it needs to implement the IEnumerable interface, implying the type <em>does</em> matter).</p>\n'}, {'answer_id': 2427596, 'author': 'Wray Smallwood', 'author_id': 291765, 'author_profile': 'https://Stackoverflow.com/users/291765', 'pm_score': 3, 'selected': False, 'text': "<p>For the afficionados that think <code>var</code> saves time, it takes less keystrokes to type:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n</code></pre>\n\n<p>than</p>\n\n<pre><code>var sb = new StringBuilder();\n</code></pre>\n\n<p>Count em if you don't believe me...</p>\n\n<p>19 versus 21</p>\n\n<p>I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)</p>\n\n<p>And it's true for every type you can think of!!</p>\n\n<p>My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.</p>\n"}, {'answer_id': 2746399, 'author': 'Daniel Earwicker', 'author_id': 27423, 'author_profile': 'https://Stackoverflow.com/users/27423', 'pm_score': 2, 'selected': False, 'text': "<p>Amazed this hasn't been noted so far, but it is common sense to use <code>var</code> for <code>foreach</code> loop variables.</p>\n\n<p>If you specify a specific type instead, you risk having a runtime cast silently inserted into your program by the compiler!</p>\n\n<pre><code>foreach (Derived d in listOfBase)\n{\n</code></pre>\n\n<p>The above will compile. But the compiler inserts a downcast from <code>Base</code> to <code>Derived</code>. So if anything on the list is not a <code>Derived</code> at runtime, there is an invalid cast exception. Type safety is compromised. Invisible casts are horrible.</p>\n\n<p>The only way to rule this out is to use <code>var</code>, so the compiler determines the type of the loop variable from the static type of the list.</p>\n"}, {'answer_id': 2866043, 'author': 'Kate Gregory', 'author_id': 203458, 'author_profile': 'https://Stackoverflow.com/users/203458', 'pm_score': 5, 'selected': False, 'text': "<p>Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.</p>\n\n<p>Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.</p>\n"}, {'answer_id': 2866052, 'author': 'Jeff Sternal', 'author_id': 47886, 'author_profile': 'https://Stackoverflow.com/users/47886', 'pm_score': 1, 'selected': False, 'text': "<p><em>Deleted for reasons of redundancy.</em></p>\n\n<p><code>vars</code> are still initialized as the correct variable type - the compiler just infers it from the context. As you alluded to, var enables us to store references to anonymous class instances - but it also makes it easier to change your code. For example:</p>\n\n<pre><code>// If you change ItemLibrary to use int, you need to update this call\nbyte totalItemCount = ItemLibrary.GetItemCount();\n\n// If GetItemCount changes, I don't have to update this statement.\nvar totalItemCount = ItemLibrary.GetItemCount();\n</code></pre>\n\n<p>Yes, if it's hard to determine a variable's type from its name and usage, by all means explicitly declare its type.</p>\n"}, {'answer_id': 2866054, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't. </p>\n\n<p>Another case of concern, in the following call you can't tell just by looking at the code the type returned by <code>CallMe</code>:</p>\n\n<pre><code>var variable = CallMe();\n</code></pre>\n\n<p>That's my main complain against var.</p>\n\n<p>I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use <code>Func</code>. Consider this code:</p>\n\n<pre><code>var callback = new Func&lt;IntPtr, bool&gt;(delegate(IntPtr hWnd) {\n   ...\n});\n</code></pre>\n\n<p><strong>EDIT</strong>: Updated the last code sample based on Julian's input</p>\n"}, {'answer_id': 2866064, 'author': 'Adam Robinson', 'author_id': 82187, 'author_profile': 'https://Stackoverflow.com/users/82187', 'pm_score': 7, 'selected': False, 'text': "<p>Neither of those is absolutely true; <code>var</code> can have both positive and negative effects on readability. In my opinion, <code>var</code> should be used when either of the following is true:</p>\n\n<ol>\n<li>The type is anonymous (well, you don't have any choice here, as it <em>must</em> be var in this case)</li>\n<li>The type is obvious based upon the assigned expression (i.e. <code>var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating()</code>)</li>\n</ol>\n\n<p><code>var</code> has no performance impacts, as it's syntactic sugar; the compiler infers the type and defines it once it's compiled into IL; there's nothing <em>actually</em> dynamic about it.</p>\n"}, {'answer_id': 2866065, 'author': 'andypaxo', 'author_id': 46575, 'author_profile': 'https://Stackoverflow.com/users/46575', 'pm_score': 1, 'selected': False, 'text': "<p>In my opinion, there is no problem in using <code>var</code> heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.</p>\n\n<p>Like any other time saver (such as auto properties for example), it <em>is</em> a good idea to understand what it is and how it works before using it everywhere.</p>\n"}, {'answer_id': 2866071, 'author': 'Martin Harris', 'author_id': 69824, 'author_profile': 'https://Stackoverflow.com/users/69824', 'pm_score': 2, 'selected': False, 'text': "<p>I think you <em>may</em> be misunderstanding the usage of var in C#. It <em>is</em> still strong typing, unlike the VB varient type so there is no performance hit from using it or not.</p>\n\n<p>Since there is no effect on the final compiled code it really is a stylist choice. Personally I don't use it since I find the code easier to read with the full types defined, but I can imagine a couple of years down the line that full type declaration will be looked at in the same way as Hungarian notation is now - extra typing for no real benefit over the information that intellisense gives us by default.</p>\n"}, {'answer_id': 2866075, 'author': 'tvanfosson', 'author_id': 12950, 'author_profile': 'https://Stackoverflow.com/users/12950', 'pm_score': 7, 'selected': False, 'text': "<p>Var, in my opinion, in C# is a <em>good thing</em><sup>tm</sup>.  Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined.  Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side.  I think this significantly increases readability without decreasing type safety.</p>\n\n<p>From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information.  If I need the type information, I can always hover over the variable (in VS) and get it.  Generally, though, explicit type information shouldn't be necessary to the reader.  For the developer, in VS you still get Intellisense, regardless of how the variable is declared.  Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a <code>List&lt;T&gt;</code>, but you want to treat it as an <code>IEnumerable&lt;T&gt;</code> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition.  In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.</p>\n"}, {'answer_id': 2866077, 'author': 'Randolpho', 'author_id': 12716, 'author_profile': 'https://Stackoverflow.com/users/12716', 'pm_score': 1, 'selected': False, 'text': "<p><code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. <code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. </p>\n\n<p>If the compiler is smart enough to figure out the type from the context, then so are you. You don't have to have it written down right there at declaration. And intellisense makes that even less necessary. </p>\n\n<p><code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. <code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. </p>\n"}, {'answer_id': 2866080, 'author': 'Guffa', 'author_id': 69083, 'author_profile': 'https://Stackoverflow.com/users/69083', 'pm_score': 4, 'selected': False, 'text': '<p>If someone is using the <code>var</code> keyword because they don\'t want to "figure out the type", that is definitely the wrong reason. The <code>var</code> keyword doesn\'t create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.</p>\n\n<p>Good reasons to use the <code>var</code> keyword are for example:</p>\n\n<ul>\n<li>Where it\'s needed,  i.e. to declare a reference for an anonymous type.</li>\n<li>Where it makes the code more readable, i.e. removing repetetive declarations.</li>\n</ul>\n\n<p>Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don\'t have to figure out the data type by first figuring out what the code does.</p>\n'}, {'answer_id': 2866088, 'author': 'Andrey', 'author_id': 283676, 'author_profile': 'https://Stackoverflow.com/users/283676', 'pm_score': 0, 'selected': False, 'text': "<p>First.</p>\n\n<p><code>var</code> is not a type and not some special feature (like c# 4.0 <code>dynamic</code>). It is just a syntax sugar. You ask compiler to infer the type by the right hand side expression. The only necessary place is anonymous types.</p>\n\n<p>I don't think that using <code>var</code> is neither good or evil, it is coding style. Personally i don't use it, but i don't mind using it by other team members.</p>\n"}, {'answer_id': 2866092, 'author': 'chris', 'author_id': 4782, 'author_profile': 'https://Stackoverflow.com/users/4782', 'pm_score': 2, 'selected': False, 'text': '<p>I think you point out the main problem with var in your question:  "I don\'t have to figure out the type".  As other have pointed out, there is a place for var, but if you don\'t know the type you\'re dealing with, there\'s a pretty good chance that you\'re going to have problems down the road - not in all cases, but there\'s enough of a smell there so that you should be suspicious.</p>\n'}, {'answer_id': 2866094, 'author': 'kastermester', 'author_id': 40240, 'author_profile': 'https://Stackoverflow.com/users/40240', 'pm_score': 2, 'selected': False, 'text': '<p>Well this one is pretty much gonna be opinionated all the way through, but I will try to give my view on it - albeit I think my view is so mixed up that you are probably not gonna get much out of it anyways.</p>\n\n<p>First of all - there\'s anonymous types, for which you need to use the "var" keyword in order to assign an object with an anonymous type as its class - there\'s not much discussion here, "var" is needed.</p>\n\n<p>For simpler types however, ints, longs, strings - so forth - I tend to put in the proper types. Mainly because it is a bit of a "lazy man\'s tool" and I don\'t see much gain here, very few keystrokes and the possible confusion it could provide later down the road just ain\'t worth it. Especially the various types for floating point numbers (float, double, decimal) confuse me as I am not firm with the postfixes in the literals - I like to see the type in the source code.</p>\n\n<p>With that said, I tend to use var alot if the type is more complex and/or it is explicitly repeated on the righthand-side of the assignment. This could be a <code>List&lt;string&gt;</code> or etc, such as:</p>\n\n<pre><code>var list = new List&lt;string&gt;();\n</code></pre>\n\n<p>In a such case, I see no use to repeat the type twice - and especially as you start changing your code and the types change - the generic types might get more and more complicated and as such having to change them twice is just a pain. However of course if you wish to code against an <code>IList&lt;string&gt;</code> then you have to name the type explicitly.</p>\n\n<p>So in short I do the following:</p>\n\n<ul>\n<li>Name the type explicitly when the type is short or cannot be read out of context</li>\n<li>Use var when it has to be used (duh)</li>\n<li>Use var to be lazy when it (in my mind) does not hurt readability</li>\n</ul>\n'}, {'answer_id': 2866100, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 3, 'selected': False, 'text': "<p>Sure, <code>int</code> is easy, but when the variable's type is <code>IEnumerable&lt;MyStupidLongNamedGenericClass&lt;int, string&gt;&gt;</code>, var makes things much easier.</p>\n"}, {'answer_id': 2866236, 'author': 'Christian Specht', 'author_id': 6884, 'author_profile': 'https://Stackoverflow.com/users/6884', 'pm_score': 3, 'selected': False, 'text': '<p>I only use var when it\'s clear to see what type is used.</p>\n\n<p>For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":</p>\n\n<pre><code>var x = new MyClass();\n</code></pre>\n\n<p>I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:</p>\n\n<pre><code>var x = MyClass.MyFunction();\n</code></pre>\n\n<p>Especially, I <strong>never</strong> use var in cases where the right side is not even a method, but only a value:</p>\n\n<pre><code>var x = 5;\n</code></pre>\n\n<p><em>(because the compiler can\'t know if I want a byte, short, int or whatever)</em></p>\n'}, {'answer_id': 2866354, 'author': 'Christopher Barber', 'author_id': 334526, 'author_profile': 'https://Stackoverflow.com/users/334526', 'pm_score': 2, 'selected': False, 'text': "<p>Apart from readability concerns, there is one real issue with the use of 'var'. When used to define variables that are assigned to later in the code it can lead to broken code if the type of the expression used to initialize the variable changes to a narrower type. Normally it would be safe to refactor a method to return a narrower type than it did before: e.g. to replace a return type of 'Object' with some class 'Foo'. But if there is a variable whose type is inferred based on the method, then changing the return type will mean that this variable can longer be assigned a non-Foo object:</p>\n\n<pre><code>var x = getFoo(); // Originally declared to return Object\nx = getNonFoo();\n</code></pre>\n\n<p>So in this example, changing the return type of getFoo would make the assignment from getNonFoo illegal.</p>\n\n<p>This is not such a big deal if getFoo and all of its uses are in the same project, but if getFoo is in a library for use by external projects you can no longer be sure that narrowing the return type will not break some users code if they use 'var' like this.</p>\n\n<p>It was for exactly this reason that when we added a similar type inferencing feature to the Curl programming language (called 'def' in Curl) that we prevent assignments to variables defined using this syntax.</p>\n"}, {'answer_id': 2866628, 'author': 'kervin', 'author_id': 16549, 'author_profile': 'https://Stackoverflow.com/users/16549', 'pm_score': 0, 'selected': False, 'text': '<p>Eric\'s answer here...</p>\n\n<p><a href="https://stackoverflow.com/questions/2590643/namespace-scoped-aliases-for-generic-types-in-c/2593664#2593664">Namespace scoped aliases for generic types in C#</a></p>\n\n<p>is related.  </p>\n\n<p>Part of the issue is that there is no strongly typed aliasing in C#.  So many developers use <em>var</em> as a partial surrogate.</p>\n'}, {'answer_id': 2866735, 'author': 'stormianrootsolver', 'author_id': 339087, 'author_profile': 'https://Stackoverflow.com/users/339087', 'pm_score': -1, 'selected': False, 'text': "<p>Don't use that, makes your code unreadable.</p>\n\n<p>ALWAYS use as strict typing as possible, crutches only makes your life hell.</p>\n"}, {'answer_id': 2866767, 'author': 'Andrew Lewis', 'author_id': 25650, 'author_profile': 'https://Stackoverflow.com/users/25650', 'pm_score': 0, 'selected': False, 'text': "<p>It's not wrong, but it can be inappropriate. See all the other responses for examples.</p>\n\n<p>var x = 5; <em>(bad)</em></p>\n\n<p>var x = new SuperDooperClass(); <em>(good)</em></p>\n\n<p>var x = from t in db.Something select new { Property1 = t.Field12 }; <em>(better)</em></p>\n"}, {'answer_id': 2866779, 'author': 'Joshua', 'author_id': 14768, 'author_profile': 'https://Stackoverflow.com/users/14768', 'pm_score': 0, 'selected': False, 'text': '<p>"The only thing you can really say about my taste is that it is old fashioned, and in time yours will be too." -Tolkien.</p>\n'}, {'answer_id': 2866857, 'author': 'Will Marcouiller', 'author_id': 162167, 'author_profile': 'https://Stackoverflow.com/users/162167', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/bb383973.aspx" rel="nofollow noreferrer"><code>var</code></a> is a placeholder introduced for the <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer"><code>anonymous types</code></a> in C# 3.0 and LINQ.</p>\n\n<p>As such, it allows writing LINQ queries for a fewer amount of columns within, let\'s say, a collection. No need to duplicate the information in memory, only load what\'s necessary to accomplish what you need to be done.</p>\n\n<p>The use of <code>var</code> is not bad at all, as it is actually not a type, but as mentioned elsewhere, a placeholder for the type which is and has to be defined on the right-hand side of the equation. Then, the compiler will replace the keyword with the type itself.</p>\n\n<p>It is particularly useful when, even with IntelliSense, the name of a type is long to type. Just write <code>var</code>, and instantiate it. The other programmers who will read your code afterward will easily understand what you\'re doing.</p>\n\n<p>It\'s like using</p>\n\n<pre><code>public object SomeObject { get; set; }\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>public object SomeObject {\n    get {\n        return _someObject;\n    } \n    set {\n        _someObject = value;\n    }\n}\nprivate object _someObject;\n</code></pre>\n\n<p>Everyone knows what\'s the property\'s doing, as everyone knows what the <code>var</code> keyword is doing, and either examples tend to ease readability by making it lighter, and make it more pleasant for the programmer to write effective code.</p>\n'}, {'answer_id': 2867274, 'author': 'Jerry Liu', 'author_id': 240951, 'author_profile': 'https://Stackoverflow.com/users/240951', 'pm_score': 0, 'selected': False, 'text': '<p><code>var</code> is good as it follows the classic <a href="http://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself" rel="nofollow noreferrer">DRY</a> rule, and it is especially elegant when you indicate the type in the same line as declaring the variable. (e.g. <code>var city = new City()</code>)</p>\n'}, {'answer_id': 2867468, 'author': 'Julie in Austin', 'author_id': 344661, 'author_profile': 'https://Stackoverflow.com/users/344661', 'pm_score': 1, 'selected': False, 'text': '<p>If you know the type, use the type.\nIf you don\'t know the type, why not?\nIf you can\'t know the type, that\'s okay -- you\'ve found the only valid use.</p>\n\n<p>And I\'m sorry, but if the best you can do is "it makes the code all line up", that\'s not a good answer.  Find a different way to format your code.</p>\n'}, {'answer_id': 3288508, 'author': 'Igor Brejc', 'author_id': 55408, 'author_profile': 'https://Stackoverflow.com/users/55408', 'pm_score': 1, 'selected': False, 'text': '<p>One good argument why vars should not be used as a mere "typing shortcut", but should instead be used for scenarios they were primarily designed for: Resharper (at least v4.5) cannot find usages of a type if it is represented as a var. This can be a real problem when refactoring or analyzing the source code.</p>\n'}, {'answer_id': 3367011, 'author': 'Glenn Doten', 'author_id': 277774, 'author_profile': 'https://Stackoverflow.com/users/277774', 'pm_score': -1, 'selected': False, 'text': '<p>If you are lazy and use var for anything other than anonymous types, you should be required to use Hungarian notation in the naming of such variables.</p>\n\n<p><code>var iCounter = 0;</code></p>\n\n<p>lives!</p>\n\n<p>Boy, do I miss VB.</p>\n'}, {'answer_id': 3466472, 'author': 'user418243', 'author_id': 418243, 'author_profile': 'https://Stackoverflow.com/users/418243', 'pm_score': 1, 'selected': False, 'text': "<p>what most are ignoring:</p>\n\n<pre><code>var something = new StringBuilder(); \n</code></pre>\n\n<p>isn't normally typed as fast as </p>\n\n<pre><code>StringBuilder something = KEY'TAB'();\n</code></pre>\n"}, {'answer_id': 4013498, 'author': 'David Mårtensson', 'author_id': 479137, 'author_profile': 'https://Stackoverflow.com/users/479137', 'pm_score': 2, 'selected': False, 'text': '<p>With LINQ another very good reason to use <code>var</code> is that the compiler can optimize the query much more.</p>\n\n<p>If you use a static list to store the result it will execute where you assign it to the list but with <code>var</code> it can potential merge the original query with later queries in the code to make more optimized queries to the database.</p>\n\n<p>I had an example where I pulled some data in a first query and then looped over and requested more data to print out a table.</p>\n\n<p>LINQ merges these so that the first only pulled the id.</p>\n\n<p>Then in the loop it added an extra join I had not done there to fetch the data I had included in the original.</p>\n\n<p>When tested this proved much more efficient.</p>\n\n<p>Had we not used <code>var</code> it had made the queries exactly as we had written them.</p>\n'}, {'answer_id': 4021071, 'author': 'Martin Olsen', 'author_id': 487233, 'author_profile': 'https://Stackoverflow.com/users/487233', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m fairly new in the C# world, after a decade as a Java professional. My initial thought was along the lines of "Oh no! There goes type safety down the drain". However, the more I read about var, the more I like it.</p>\n\n<p>1) Var is every bit as type safe as an explicitly declared type would be. It\'s all about compile time syntactic sugar.</p>\n\n<p>2) It follows the principle of DRY (don\'t repeat yourself). DRY is all about avoiding redundancies, and naming the type on both sides is certainly redundant. Avoinding redundancy is all about making your code easier to change.</p>\n\n<p>3) As for knowing the exact type .. well .. I would argue that you always have a general idea is you have an integer, a socket, some UI control, or whatever. Intellisense will guide you from here. Knowing the exact type often does not matter. E.g. I would argue that 99% of the time you don\'t care if a given variable is a long or an int, a float or a double. For the last 1% of the cases, where it really matters, just hover the mouse pointer above the var keyword.</p>\n\n<p>4) I\'ve seen the ridiculous argument that now we would need to go back to 1980-style Hungarian warts in order to distinguish variable types. After all, this was the only way to tell the types of variables back in the days of Timothy Dalton playing James Bond. But this is 2010. We have learned to name our variables based upon their usage and their contents and let the IDE guide us as to their type. Just keep doing this and var will not hurt you.</p>\n\n<p>To sum it up, var is not a big thing, but it is a really nice thing, and it is a thing that Java better copy soon. All arguments against seem to be based upon pre-IDE fallacies. I would not hesitate to use it, and I\'m happy the R# helps me do so.</p>\n'}, {'answer_id': 8207749, 'author': 'Mel', 'author_id': 642269, 'author_profile': 'https://Stackoverflow.com/users/642269', 'pm_score': 0, 'selected': False, 'text': "<p>var is the way to deal with anonymous types, whether from LINQ statements or not. Any other use is heavily dependent on who will read your code and what guidelines are in place. </p>\n\n<p>If you are the only audience or your audience is comfortable with using var or is very familiar with your code then I guess it doesn't matter. If you use it like: <strong>var s = new SqlConnection()</strong> then it largely doesnt matter and probably improves code readability. If people aren't too picky and its okay for them to do a little work to know the type when its not apparent (which is not needed in most cases, how you use it in the following statements would usually explain everything) then its alright.</p>\n\n<p>But if you have picky, close-minded teammates who love to whine or if your company's design guidelines specifically forbid using var when the type is not obvious then you will most likely meet heavy opposition. </p>\n\n<p>If using var makes your code insanely difficult to read, you will probably get shot by using var even if its probably your app design that is to blame.</p>\n\n<p>If var introduces ambiguity (sort of like your IEnumerable/IEnumerable example), just don't use it and be explicit. But var does have its conveniences and in some cases, IMHO, even improves readabilty by reducing clutter.</p>\n"}, {'answer_id': 8236836, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>var is like the dotted spaces in kids' books where kids have to fill it. Except in this case the Compiler will fill it with the right type which is usually written after the = sign.</p>\n"}, {'answer_id': 8294143, 'author': 'Muhammad Atif Agha', 'author_id': 727794, 'author_profile': 'https://Stackoverflow.com/users/727794', 'pm_score': 0, 'selected': False, 'text': '<p>Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. </p>\n\n<p>// z is compiled as an int</p>\n\n<pre><code>var z = 100;\n</code></pre>\n\n<p>// s is compiled as a string below</p>\n\n<pre><code>var s = "Hello";\n</code></pre>\n\n<p>// a is compiled as int[]</p>\n\n<pre><code>var a = new[] { 0, 1, 2 };\n</code></pre>\n\n<p>// expr is compiled as IEnumerable\n// or perhaps IQueryable</p>\n\n<pre><code>var expr =\n    from c in customers\n    where c.City == "London"\n    select c;\n</code></pre>\n\n<p>// anon is compiled as an anonymous type</p>\n\n<pre><code>var anon = new { Name = "Terry", Age = 34 };\n</code></pre>\n\n<p>// list is compiled as List                             </p>\n\n<pre><code>var list = new List&lt;int&gt;();\n\nvar can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.\n</code></pre>\n\n<p>var cannot be used on fields at class scope.</p>\n\n<p>Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);</p>\n\n<p>Multiple implicitly-typed variables cannot be initialized in the same statement.</p>\n\n<p>If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.</p>\n'}]
['https://Stackoverflow.com/questions/41479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394/']