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.....