Hi Folks,
In this post I’ll talk briefly about how to create objects with dynamic fields on the fly in a C# application.
First of all, why is this important?
An example is if you’re developing an API that returns some data where the fields are calculated at runtime.
This means you can’t anticipate what it would be before hand and create classes ahead of time.
In C# we use what is called ExpandoObject.
ExpandoObject represents an object whose members can be dynamically added or removed at runtime.
To create an ExpandoObject instance, you do something like
dynamic row = new ExpandoObject();
To set a field whose name you know at compile time, do something like
row.SomeField = somevalue
To set a field whose name you don’t know ahead of time, but whose name is stored in the value of another object, say fieldNameHolder, to some value stored in a variable, say fieldValueHolder, do something like
(IDictionary<string, object>row).Add(fieldNameHolder, fieldValueHolder);
That’s all for now. Till next time, happy software development.
References
ExpandoObject Class. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-9.0M