1

I love implicit typing in C# for local variables:

var Beer = new Malt.Beer();

instead of:

Malt.Beer Beer = new Malt.Beer();

I don't suppose this can be extended to fields can it?

public var Beer = new Malt.Beer();

instead of:

public Malt.Beer Beer = new Malt.Beer();

It doesn't compile but wondered I'd just got the syntax wrong or implicit variables (var) can't be used in this scope?

Rob Nicholson
  • 1,943
  • 5
  • 22
  • 37
  • I do not believe that is possible. `var` only works inside methods. – Nathan A Sep 23 '15 at 16:25
  • var to my way of thinking was a big mistake by microsoft. Think about it, when you use Var the compiler has to convert to the correct object type. If your explicit it doesn't. Also on large programs, when your trying to debug, quite often you have to hover over the variable to find out what it is as opposed to seeing straight away the object type. You also loose intellisense on variables of type var. Var should only be used really in conjunction with generics where it may be of differing types. – bilpor Sep 23 '15 at 16:30
  • 2
    @bilpor most of what you just said is completely wrong. The compiler doesn't have to "convert" anything - the variable is always strongly typed. `int i = 10;` and `var i = 10;` are exactly the same and result in the exact same IL. You also don't lose Intellisense at all, it still works perfectly. – Dave Zych Sep 23 '15 at 16:35
  • @bilpor I think you meant it should only be used with anonymous classes, not generics. – juharr Sep 23 '15 at 16:35
  • @Dave Zych must be my version of VS2013 Pro then....Whenever I use var, I dont get intellisense against the object I'm setting it to. – bilpor Sep 24 '15 at 08:43

2 Answers2

2

From the MSDN programming guide for C#:

Remarks The following restrictions apply to implicitly-typed variable declarations: var 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.

  • var cannot be used on fields at class scope.
  • 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);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • 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.
Pseudonym
  • 2,052
  • 2
  • 17
  • 38
1

Fields in C# cannot be implicitly typed, sorry. I think it has something to do with the scope of fields as opposed to local variables.

BMaze
  • 19
  • 6