Search code examples
c#usingvar

var keyword without 'using someNamespace'


How does Visual Studio/intellisense know what to do with a variable declared as var even if you don't include the necessary using declaration at the top?

For example, I have class MyDomainObject defined in a different namespace If I don't declare using TheOtherNameSpace; in the file the following code won't compile:

private void Foo()
{
   MyDomainObject myObj = new MyDomainObject(); 
   // Doesn't know what this class is
}

But if I use var

var myObj = new MyDomainObject();

This will compile, and intellisense knows exactly what I can with it.

So how the heck does it know what the type is without the using?

(And as an aside, if it knows without the using, why do we need usings at all?!)


Solution

  • Your example with a constructor won't work, but a slightly more involved situation will. For example, suppose you have three types:

    • class Foo in namespace N1
    • class Bar in namespace N2
    • class Baz in namespace N3

    Now suppose Bar has a method which returns an instance of Foo:

    public static Foo GetFoo() { ... }
    

    Here, Bar.cs would need a using directive for N1, unless it specified the name in full.

    Now suppose that we have this code in Baz:

    using N2;
    ...
    var foo = Bar.GetFoo();
    

    That will compile, but

    using N2;
    ...
    Foo foo = Bar.GetFoo();
    

    won't. The reason is that using directives are only there so that the compiler knows what the name "Foo" means - what its fully qualified name is. In the first snippet, Bar.GetFoo() is effectively declared to return N1.Foo, so the compiler is fine. In the second snippet, the compiler first sees "Foo" and doesn't know anything about N1, so doesn't know how to look it up.