New! GraphQL.NET Cookbook by Senthil Kumar Balu

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");
Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.