Search code examples
c#c#-4.0c#-3.0implicit-typing

Implicity typed class member


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


Solution

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