Home > DeveloperSection > Forums > How can var know of an undefined type?
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    February-03-2014 12:07 AM

 C# C# 
Ratings:


 1 Reply(s)
 1086  View(s)
Rate this:

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

Total Post:411

Points:2881
Posted on    February-03-2014 12:59 AM

Hi Royce,

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.



Don't want to miss updates? Please click the below button!

Follow MindStick