Implicity typed class member [duplicate]
-
15-11-2019 - |
سؤال
Possible Duplicate:
Using var outside of a method
I've searched for this a bit, but am not too sure of the search terms so didn't find anything.
Why can't i do this:
class foo
{
var bar = new Dictionary<string, string>();
}
Guessing there must be a very good reason, but i can't think of it!
I'm more interested in the reasoning, rather than the because "C# doesn't let you" answer.
EDIT: Edited Dictionary
declaration, sorry (just a typo in the example)!
المحلول
2 reasons:
- The Dictionary requires Key and Value generic parameters
- You cannot write variables like this directly inside a class => you could use fields, properties or methods
So:
class foo
{
private Dictionary<string, string> bar = new Dictionary<string, string>();
}
As to why you cannot do this:
class foo
{
private var bar = new Dictionary<string, string>();
}
Eric Lippert has covered it in a blog post.
نصائح أخرى
You did not specify a type for the key, it should be:
class foo
{
Dictionary<string,string> bar = new Dictionary<string,string>();
}
Edit: And it's not allowed to use "var" in case of class fields.
A dictionary needs two parameters, a key type and a value type.
var bar = new Dictionary<string, string>();
"Dictionary" means a collection of key/value pairs. In real-world, a dictionary of worlds is a book containing "Words" and "Definitions", here "Word" is key and "Definition" is value. So this is obvious that you can't ignore "value" when instantiating a Dictionary<TKey, TValue>
.
A dictionary is a class for mapping a set of keys to a set of values, so you need to specify a type parameter for both the key and value. For example, if you want to lookup a share price based on its stock symbol, you might use:
var stocks = new Dictionary<string, decimal>();
stocks.Add("MSFT", 25.5M);
stocks.Add("AAPL", 339.87M);