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.
,
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.
,
Sorry, my C#’s rusty, so Ill tackle this in VB. Only way I can figure to do it is to use an Object type. Check out the property type definition and instantiation method below:
Private m_myVal As Object
Public Property myVal() As Object
Get
Return m_myVal
End Get
Set(ByVal value As Object)
m_myVal = value
End Set
End Property
Public Sub New(ByVal valType As String, ByVal val As Object)
If valType = "string" Then
myVal = CType(val, String)
ElseIf valType = "date" Then
myVal = CType(val, Date)
End If
End Sub
Then, for example, create a new instance of the class as:
Dim myDynamicClass as New Class1("date","10/21/2010")
Your myval property will have a date typed value stored.