Tag Archives: array of object

Dynamic Object in C#

In my experience there was a need to create an object and its properties dynamically. Namely as follows:

thisIsMyObject.MyProperty1 = "AnyValueOfAnyType";
thisIsMyObject.MyProperty2 = true;
thisIsMyObject.MyProperty3 = 1;

To do this there could be different approaches like using a dictionary

Dictionary<string,object> c = new Dictionary<string,object>();
//adding a value
c.Add("MyProperty1", "AnyValueOfAnyType");
c.Add("MyProperty2", true);
c.Add("MyProperty3", 1);
//getting the value
c["MyProperty1"]; //AnyValueOfAnyType
c["MyProperty2"]; //true
c["MyProperty3"]; //1

But you may also use a dynamic object like as follows

var c = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>; //namespace for note only
//adding a value
c["MyProperty1"] = "AnyValueOfAnyType";
c["MyProperty2"] = true;
c["MyProperty3"] = 1;
//getting the value
c["MyProperty1"]; //AnyValueOfAnyType
c["MyProperty2"]; //true
c["MyProperty3"]; //1

This way its more presentable and like using an array.

God Bless!

Thanks,
Thomie