How to create own dynamic type or dynamic object in C#?

C#DynamicViewbag

C# Problem Overview


There is, for example, the ViewBag property of ControllerBase class and we can dynamically get/set values and add any number of additional fields or properties to this object, which is cool. I want to use something like that, beyond MVC application and Controller class in other types of applications. When I tried to create dynamic object and set its property like this:

1. dynamic MyDynamic = new { A="a" };
2. MyDynamic.A = "asd";
3. Console.WriteLine(MyDynamic.A);

I've got RuntimeBinderException with message Property or indexer '<>f__AnonymousType0.A' cannot be assigned to -- it is read only in line 2. Also, I suspect it's not quite what I'm looking for. Maybe is there some class which allows me to do something like:

??? MyDynamic = new ???();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = DateTime.Now;
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

with dynamic adding and setting properties.

C# Solutions


Solution 1 - C#

dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() => 
{ 
    return 55; 
});
Console.WriteLine(MyDynamic.MyMethod());

Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.

Solution 2 - C#

I recently had a need to take this one step further, which was to make the property additions in the dynamic object, dynamic themselves, based on user defined entries. The examples here, and from Microsoft's ExpandoObject documentation, do not specifically address adding properties dynamically, but, can be surmised from how you enumerate and delete properties. Anyhow, I thought this might be helpful to someone. Here is an extremely simplified version of how to add truly dynamic properties to an ExpandoObject (ignoring keyword and other handling):

// my pretend dataset
List<string> fields = new List<string>();
// my 'columns'
fields.Add("this_thing");
fields.Add("that_thing");
fields.Add("the_other");

dynamic exo = new System.Dynamic.ExpandoObject();

foreach (string field in fields)
{
    ((IDictionary<String, Object>)exo).Add(field, field + "_data");
}

// output - from Json.Net NuGet package
textBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exo);

Solution 3 - C#

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

Solution 4 - C#

dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};

Solution 5 - C#

var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

var data = new { studentId, StudentName };

Solution 6 - C#

You can use ExpandoObject Class which is in System.Dynamic namespace.

dynamic MyDynamic = new ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.SomeProperty = SomeValue
MyDynamic.number = 10;
MyDynamic.Increment = (Action)(() => { MyDynamic.number++; });

More Info can be found at ExpandoObject MSDN

Solution 7 - C#

dynamic MyDynamic = new ExpandoObject();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDmytroView Question on Stackoverflow
Solution 1 - C#Mario SView Answer on Stackoverflow
Solution 2 - C#AlienFromCAView Answer on Stackoverflow
Solution 3 - C#nothrowView Answer on Stackoverflow
Solution 4 - C#smedasnView Answer on Stackoverflow
Solution 5 - C#RockView Answer on Stackoverflow
Solution 6 - C#Kishore KumarView Answer on Stackoverflow
Solution 7 - C#DaveczView Answer on Stackoverflow