Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...