Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Custom Objects at runtime in C#

I want to create custom objects in C# at runtime, the objects will have properties imported from an xml file. The xml file looks something like this:

<field name="FirstName" value="Joe" type="string" />
<field name="DateAdded" value="20090101" type="date" />

I would like to create objects in c# that have properties such as FirstName and DateAdded and that have the correct type for the properties. How can I do this? I have tried using a function with if statements to determine the type based on the "type" attribute but I would like to evaluate the types on the fly as well.

Thanks.

like image 257
jangeador Avatar asked Dec 29 '25 12:12

jangeador


1 Answers

You can do this via CodeDOM, or more easily using dynamic and ExpandoObject.

However, realize that, without knowing the types in advance, it's difficult to use them effectively. Often, making a Dictionary<TKey, TValue> or similar option is an easier choice.

like image 165
Reed Copsey Avatar answered Jan 01 '26 04:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!