How can the implicit type variable var know a type that is not defined in the scope (using using)?
Example:
This is ok
public class MyClass
{
public void MyMethod
{
var list = AStaticClass.GetList();
}
}
But this is not ok
public class MyClass
{
public void MyMethod
{
List<string> list = AStaticClass.GetList();
}
}
In the last code snippet I have to add using System.Collections.Generic; for it to work.
How does this work?
When the compiler does the type inference it replaces
varwithSystem.Collections.Generic.List<string>and your code becomes:But since the compiler spits IL, the following C# program (without any
usingstatements):and the
Mainmethod looks like this:As you can see the compiler inferred the type from the right hand-side of the assignment operator and replaced
varwith the fully qualified type name.