tags:

views:

84

answers:

3

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

+6  A: 

Short answer is that it doesn't.

There must be some other reason for the behavior and difference you're seeing.

Can you reproduce the problem with a short, but complete, program so that you could post it here?

There is nothing magical about the var keyword, it simply infers the type needed based on the expression on the right hand side of the assignment (in this case), so there is no reason why one of the code pieces should work better than the other.

Lasse V. Karlsen
A: 

It knows the fully-qualified type of the object because this type is in one of the referenced assemblies.

using SomeNamespace is only a shorthand making it possible to say MyType instead of SomeNamespace.MyType.

Gart
+6  A: 

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.

Jon Skeet
Thanks Jon, both for the answer and for managing to understand the question given my poor example
RichK
+1 Excellent and concise explanation
Jim Schubert