Dmytro Tsiniavskyi Dmytro Tsiniavskyi - 11 months ago 50
C# Question

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

There, is for example, ViewBag property of

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
class in other types of applications. When I tried to create dynamic object and set it's property like below:

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

I've got
with message Property or indexer '<>f__AnonymousType0.A' cannot be assigned to -- it is read only in line 2. Also I suggest It's not quite what I'm looking-for. Maybe is there some class which can allow 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.

Answer Source
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; 

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