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?
Pravesh Singh
03-Feb-2014When the compiler does the type inference it replaces var with System.Collections.Generic.List<string> and your code becomes:
But since the compiler spits IL, the following C# program (without any using statements):
and the Main method looks like this:
As you can see the compiler inferred the type from the right hand-side of the assignment operator and replaced var with the fully qualified type name.