Sharing “var” across the method

One of the biggest limitation in “var” is that it cannot be shared across the methods. So if you are doing something using that keyword then you have to stick to the local. I was reading Alex’s Blog where he explained it very nicely,

 

Here is my implementation,

 

Create an Extension method

 

static class MyClass

{

    //Create Extension Method to covert the var

    public static T CastVar<T>(this object obj, T anyType)

    {

        return (T)obj;

    }

}

 

 

Now suppose you want to get output of type “var” from any method,

 

public static object GetVAR()

{

    var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    return (object)list;

}

 

Retrieve it to an object.

object o = GetVAR();

 

Next is the tricky part, as per Alex

This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.”

 

You need to know the shape of the object to put it again back to “var” type.

var o1 = o.CastVar(new List<int>{1});

 

Now this iteration will work perfectly fine as if you are working with any other local “var”.

 

foreach (int i in o1)

{

    Console.WriteLine(i);

}

 

I have tested this for LINQ to SQL where we use “var” very frequently,

 

static void Main(string[] args)

{

    object o = GetVAR();

               

    var query = o.CastVar(new[] {new {CID = "", Company = ""}});

    foreach (var c in query)

    {

         Console.WriteLine("{0} - {1}", c.CID, c.Company);

    }

}

public static object GetVAR()

{

    NWDataContext db = new NWDataContext();

    var q = from c in db.Customers

            where c.City == "London"

            select new

            {

                CID = c.CustomerID,

                Company = c.CompanyName

            };

    return (object)q.ToArray();

}

 

Namoskar!!!