-1

The type inference VAR,serves only to be recognized by the program only if he has to go to replace "int "string" etc.? If yes,would it not be better to always use VAR?

  • Not even sure what you mean, use type inference when you want easy refactoring. Still need concrete types for casting – Callum Linington Sep 11 '14 at 21:54
  • 2
    No, personally I prefer to explicity write int or string or whatever because it is clearer. But var is fine if your variables are named well or it's obvious what you're doing. – eddie_cat Sep 11 '14 at 21:54
  • 3
    You cannot always use var, at least for expressions like var myVar = null; – Valentin P. Sep 11 '14 at 21:55
  • Using it explicitly makes refactoring so difficult! – Callum Linington Sep 11 '14 at 21:55
  • var keyword makes refactoring easier - if you wanted to change return types of methods, etc. – Donal Sep 11 '14 at 21:56
  • http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp – thepirat000 Sep 11 '14 at 21:57
  • You can always use var except in two instances: when you want to initialize a variable to null and when you're assigning a Delegate to a variable. I always use var whenever it's possible. – brz Sep 11 '14 at 21:59

3 Answers3

3

There are pros and cons to using the var keyword.

What are the benefits of using var

  • Dont Repeat Yourself (DRY) – Redundant code should be avoided.
  • Faster creation of code
  • Calls for improved naming of variables – can work as a reminder for descriptive naming
  • Improved readability – in some cases (where the repeated type is long and complex)
  • Less code modification if you later need to change the type
  • Clearer distinction of when you really want to specify the type

The disadvantages of using var

  • Loss of readability – in some cases (where the type isn’t obvious)
  • Changes to the type could introduce bugs which the compiler otherwise would have caught for the developer

+ Good:

  • var numbers = new int[] {1, 2, 3, 4};
  • var stringbuilder = new StringBuilder();
  • var cars = new List();
  • var orders = new Dictionary();

+/- OK with either (but prefer explicit declaration):

  • int pages = 10;
  • string username = “john”;
  • var username = “john”;
  • var order = GetOrder(orderId); // ok if the type is Order, otherwise not
  • for (var x = 1; x < 10; x++)

- Bad:

  • var settings = GetInboxSettings(); // not obvious at all
  • var userId = GetUserId(); // ambigous, is this guid, string, int or a custom UserId object?
  • Dictionary orders = new Dictionary(); // redundant
Claies
  • 22,124
  • 4
  • 53
  • 77
3

In MSDN, there are some guidelines. Usually, it helps readability in this cases:

  1. Declaring a variable with a primitive value: var i = 0
  2. Declaring an object with a constructor: var logText = new StringBuilder()
  3. Inside for and foreach statements: foreach (var word in dictionary)
  4. Dealing with LINQ queries.

Also, note that there's a case where var is obligatory, in the construction of anonymous types.

Mephy
  • 2,978
  • 3
  • 25
  • 31
  • +1 for mentioning anonymous types, which was probably the main reason var was introduced. – phoog Sep 11 '14 at 22:09
  • Does this answer the original question? – Dennis Traub Sep 11 '14 at 22:09
  • @DennisTraub the first question in the question is "when [to] use type inference." This answer answers that question. – phoog Sep 11 '14 at 22:10
  • @DennisTraub its kinda hard to decipher what the original question is. To me, looks like OP wanted to know when to use `var`, and I answered it properly. – Mephy Sep 11 '14 at 22:10
  • @Mephy I'd interpret it differently. OP seems to be asking if there is any reason to *not* use `var` – Dennis Traub Sep 11 '14 at 22:11
2

I usually opt for var and try to choose speaking variable names. But in some cases using the actual type can be very helpful:

  • In some special cases it might make the code more readable to use the actual type.

  • You might want to initialize a variable with null (which is an arguable practice), wich prevents the compiler from infering the type.

  • Quite often, especially when coding against interfaces and abstractions, you want to explicitly use an interface or a base type as in IEnumerable<Item> items = new List<Item>()

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • 1
    what about refactoring though.... – Callum Linington Sep 11 '14 at 21:56
  • Can you give a real example when "you want to explicitly use an interface or a basetype as in IEnumerable items = new List()"? – Valentin P. Sep 11 '14 at 21:57
  • I think his point is that you can't *always* use var... which is what the question is asking. Not "are there positive aspects to using var?" – eddie_cat Sep 11 '14 at 21:57
  • 1
    @No1_Melman sometimes its actually nice, because it will cause a compile time error and you can make sure the change didn't break anything else. Leave it there and you could have some sneaky errors show up afterwards because *you really needed* that variable to be a float, and not a double. – BradleyDotNET Sep 11 '14 at 21:58
  • 1
    @ValentinP. sure: `IEnumerable items = new List(); if (something) items = items.Where(i => i.Value > threshold);` – phoog Sep 11 '14 at 21:59
  • 2
    @No1_Melman Automatic refactoring won't be a problem with explicit types, given you use the proper tools. – Dennis Traub Sep 11 '14 at 21:59
  • @phoog, ok, you are right :) I remember another one case. It is usefull for Explicit Interface Method Invocation – Valentin P. Sep 11 '14 at 22:03
  • @ValentinP. Basically because you should try to follow two of the most basic principles of object-oriented programming: *1. Code against abstractions instead of concrete implementations* and *2. Favor composition over inheritance*. Both of which can be found in the OO-classic *Design Patterns* by Gamma et al. – Dennis Traub Sep 11 '14 at 22:07
  • @ValentinP. this is for calling an extension method that is defined on `IEnumerable` and returns `IEnumerable`. The variable `items` therefore can't have the type `List`. Another solution would be to use a second variable, but I've used this technique quite a bit and I find it is very useful to avoid declaring the second variable. – phoog Sep 11 '14 at 22:07
  • @DennisTraub, declaring of local variable has nothing impact on SOLID, GoF, OOP, etc. That's why I asked. – Valentin P. Sep 11 '14 at 22:09
  • @ValentinP. Of course it does. – Dennis Traub Sep 11 '14 at 22:10
  • @DennisTraub, there were presented at least two cases - EIMI by me and "one variable optimization" by phoog. Both are mostly of "technical" nature. It would be great if you provide a GoF pattern where explicit (!) local variable cast makes sense. – Valentin P. Sep 11 '14 at 22:16
  • I'm not speaking of patterns, I'm speaking of principles. (The first part of the book, the one without pictures). And I'm not talking about explicit local variable casting either. – Dennis Traub Sep 11 '14 at 22:37
  • @DennisTraub, ok, but we discuss here certain case - using of var keyword, which is applicable only for local variable declaration. Using of explicit classes instead of var is equally to "safe explicit" cast. I am not talking about class fields or method arguments. There are no principles applicable to this certain case. Blind adherence to "some principles" always ends up in overkill. It is all about what you are writing now. I think that talking about principles you should understand the reasons why it was developed: http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf – Valentin P. Sep 11 '14 at 22:56