0

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)!

Community
  • 1
  • 1
George Duckett
  • 31,770
  • 9
  • 95
  • 162

5 Answers5

2

2 reasons:

  1. The Dictionary requires Key and Value generic parameters
  2. 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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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.

BitKFu
  • 3,649
  • 3
  • 28
  • 43
0

A dictionary needs two parameters, a key type and a value type.

var bar = new Dictionary<string, string>();
JWL_
  • 829
  • 5
  • 15
0

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

Alireza Maddah
  • 5,718
  • 2
  • 21
  • 25
0

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);
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110