Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can var know of an undefined type?

Tags:

syntax

c#

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?

like image 297
FatAlbert Avatar asked Aug 15 '12 11:08

FatAlbert


2 Answers

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.

like image 118
Darin Dimitrov Avatar answered Sep 20 '22 05:09

Darin Dimitrov


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.

like image 39
Fedor Hajdu Avatar answered Sep 20 '22 05:09

Fedor Hajdu