1

I'm using vim + omnisharp/syntastic for some unity3d development in C#.

When I declare a variable using the actual type, for instance

string[] myArray = new string[5];

I get a warning message telling me to use the 'var' keyword instead.

Is there any reason for that (i.e. performance, established code style, etc) ? Are there any pros/cons ?

Running Turtle
  • 12,360
  • 20
  • 55
  • 73
  • 2
    Are you sure it's actually a *warning* rather than just an offer to refactor for you? (No, there are no performance benefits. It's a somewhat personal matter of style.) – Jon Skeet Jun 23 '15 at 08:15
  • It's about readability. If you can infer the type from the right side of the assignment (right of =), there's no need to repeat yourself. It's also shorter to write. – cbr Jun 23 '15 at 08:15
  • 1
    Also, I recommend the reading of this text, on the use (or not) of "var" :) http://www.infoq.com/news/2008/05/CSharp-var and also this interesting text (and comments): http://blogs.msdn.com/b/ericlippert/archive/2011/04/20/uses-and-misuses-of-implicit-typing.aspx – Jauch Jun 23 '15 at 08:20
  • 2
    But it shouldn't be used *always*. Some people even replace `int` with `var`. Don't do that. Use it for generic types and LINQ-queries but don't just replace everything with `var`. – Dennis_E Jun 23 '15 at 08:20
  • @Jauch Interesting that he quotes Dare Obasanjo of RSS Bandit. That app just got bloated and unresponsive over the years. –  Jun 23 '15 at 08:44
  • Yup, refactor bitching about completely irrelevant thing. – IS4 Jun 23 '15 at 09:02
  • @MickyDuncan, The article is interesting mainly because it's old. So, how things evolved from them to now? But in fact, there are many more questions that must be taken into account when dealing with a project, not only the use of "var" ;) – Jauch Jun 23 '15 at 11:09
  • @Jauch Agreed. I must say I liked the MSDN blog link you provided –  Jun 23 '15 at 12:02

1 Answers1

3

var means the compiler will determine the explicit type of the variable, based on the usage.

One pro is that it requires less typing to declare variables and it's more readable, but can be used only for local scope variables.

Also with var, you don't have explicit reference to type, as compiler infers type for you, so you don't need to import namespace when you need a temporary variable.(using directive)

Thanos Markou
  • 2,587
  • 3
  • 25
  • 32