HOW CAN VAR KNOW OF AN UNDEFINED TYPE?

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
C# 
C#
 1348  View(s)
Ratings:
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?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How can var know of an undefined type?

    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.


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!