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?
How does this work?
When the compiler does the type inference it replaces var
with System.Collections.Generic.List<string>
and your code becomes:
public class MyClass
{
public void MyMethod
{
System.Collections.Generic.List<string> list = AStaticClass.GetList();
}
}
But since the compiler spits IL, the following C# program (without any using
statements):
public class Program
{
static void Main()
{
var result = GetList();
}
static System.Collections.Generic.List<string> GetList()
{
return new System.Collections.Generic.List<string>();
}
}
and the Main
method looks like this:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: call class [mscorlib]System.Collections.Generic.List`1<string> Program::GetList()
L_0005: pop
L_0006: ret
}
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.
Compiler actually knows the type. Even though you didn't shorten it with using compiler can still replace 'var
' with full type definition with namespaces System.Collections.Generic.List<string>
... the same way you could define your variable with that line without 'using' directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With