How to build C# objects dynamically ?

In this blog post , lets have a look at the usage of ExpandoObject in C# to create the C# objects dynamically.

ExpandoObject was initially introduced in C# 4.0 which was also incidentally part of Dynamic Language Runtime (DLR).

This lets the developers to add the members like properties or events at runtime.

We can use the ExpandoObject to create an object at runtime to hold the property MovieName as shown below.

dynamic expandoObj = new ExpandoObject();
expandoObj.MovieName = "Bigil";

You might have a scenario where you want to create the object and the propertyname has to be dynamic.

For example , imagine that you want the property name MovieName1 , MovieName2 etc .

You can try the below

var expandoObj = new ExpandoObject() as IDictionary<string, Object>;
expandoObj.Add("MovieName1", "bigil");

Leave a Reply

Your email address will not be published. Required fields are marked *