Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var keyword without 'using someNamespace'

Tags:

c#

var

using

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

like image 904
RichK Avatar asked Apr 13 '26 17:04

RichK


1 Answers

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.

like image 160
Jon Skeet Avatar answered Apr 16 '26 07:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!