The var keyword without 'using someNamespace'

How does Visual Studio / intellisense know what to do with a variable declared as var, even if you did not specify the required declaration usingat the top?

For example, I have a class MyDomainObjectdefined in a different namespace. If I do not declare using TheOtherNameSpace;in the file, the following code will not 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 compiles and intellisense knows exactly what I can with it.

So how the hell knows what a type is without using?

(And aside, if he knows without using, why should we usingeven ?!)

+3
source share
3 answers

, . , , :

  • Foo N1
  • Bar N2
  • Baz N3

, Bar , Foo:

public static Foo GetFoo() { ... }

Bar.cs using N1, .

, Baz:

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

,

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

. , , , "Foo" - . Bar.GetFoo() return N1.Foo, . "Foo" N1, , .

+6

: .

- , .

, , ?

var , , ( ), , , .

+6

He knows the fully qualified type of the object, because this type is in one of the reference assemblers.

using SomeNamespace- this is only a reduction, allowing instead to SomeNamespace.MyTypesay MyType.

0
source

Source: https://habr.com/ru/post/1744519/


All Articles