tags:

views:

173

answers:

3

I wanted to use the var keyword to declare a field in my class however var only seems to work inside methods.

The code I have looks like:

public static Dictionary<string, string> CommandList = new Dictionary<string, string>{};

and I wanted to have:

public static var CommandList = new Dictionary<string, string>

How come this isn't possible?

+3  A: 

The short answer is because the spec says it's not legal. ;-)

Generally, this is not what you want to do anyway. The type of the member should be IDictionary<string, string> not Dictionary<string, string>. It's a small nit but generally it's better to use an interface in an externally visible object so you can change the type later without affecting the clients of the code. The compiler is just giving you a little nudge to guide you that direction.

James Keesey
-1 it has nothing to do with whether or not you're using an interface or a concrete type
Pete Kirkham
-1 agree with Pete. The error is nothing to do with "being nudged in the right direction"
Rob Levine
I didn't say that it did. I said it was because the spec said so. Unlike Eric Lippert, I cannot make statements about WHY a choice was made as I wasn't there. However, I believe that even if it weren't as difficult as EL describes below, that they would have chosen not to for the reason I listed. It's a bad idea to expose the internal information of the actual type in a variable in the interface of an object. And I was hinting that the question was leading to a bad decision. Maybe too subtle.
James Keesey
Sorry James - maybe I misunderstood what you were saying but if so, maybe it could be clearer stated. I agree that for a publicly visible type it is probably better design to expose the interface rather than the implementation. However, I read the bit "The compiler is just giving you a little nudge to guide you that direction." as saying that the compiler was giving you a hint about this design issue. Which it isn't.
Rob Levine
+12  A: 

My article on the subject:

http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx

Eric Lippert
That article is good stuff. Very in-depth on the how and why.
Jim Dagg
+3  A: 

From the C# reference

  • Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var.

Also from The C# Programming Reference

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

It just isn't intended for the usage you have in mind.

It's primary aim is to allow the support of anonymous types in your code, with the added advantage of allowing a nice terse way of specifying local variables.

Rob Levine
+1 for quoting the spec and giving a reference
John Burton