Tuesday, 11 February 2014

C# Using anonymous objects with dynamic programming

Imagine that we need to assign property on the fly to an object and later access the same property in the method,well now we can do it using dynamic programming.

Let's see it in action.

void CreateObject()
{
    var person = new { Name = "Shankar", Age = 26 };
    UseObject(person);
}

void UseObject(object o)
    //This will NOT work!
    Console.Write("The name is . . . ");   
    Console.WriteLine(o.Name);
}  

As you can see we are interested in accessing the property of the person object 
but the above code will not compile at all because the object doesn't have the 
Name property. So how can we access that dynamic property which we had assigned?
The answer is yes we can access it using dynamic keyword.


void UseObject(dynamic o)
{    //This will work!
    Console.Write("The name is . . . ");   
    Console.WriteLine(o.Name);
}
Yes, now we can access the Name property of the person object.
Hope it helps someone.....





1 comment:

  1. Slot machines in Vegas - Dr.MCD
    A guide to 사천 출장안마 playing 강원도 출장마사지 video slots online at Dr.MCD's Las Vegas Casino 평택 출장샵 and Hotel. 경상북도 출장샵 Play demo for real money on Slot Machines Online.‎How to Play · 구미 출장샵 ‎Best Casino Sites · ‎How to Win Casino Games

    ReplyDelete