There, is for example, ViewBag property of ControllerBase
class and we can dynamically get/set values and add any number of additional fields or properties to t
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.
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;
dynamic MyDynamic = new ExpandoObject();
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);
var data = new { studentId = 1, StudentName = "abc" };
Or value is present
var data = new { studentId, StudentName };
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