开发者

Using var outside of a method

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>开发者_StackOverflow CommandList = new Dictionary<string, string>{};

and I wanted to have:

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

How come this isn't possible?


My article on the subject:

Why no var on fields?

To summarize:

  1. If we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.

  2. What if there are long chains, or even cycles in those references? All of those algorithms would have to be rewritten and tested in a world where top-level type information is being determined from them rather than being consumed by them.

  3. If you have "var" fields then the initializer could be of anonymous type. Suppose the field is public. There is not yet any standard in the CLR or the CLS about what the right way to expose a field of anonymous type is.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜