3

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.

3
  • Why do you need an object? Can't you just use the xml? A dictionary? Commented Oct 21, 2010 at 2:21
  • You must tell us the version of C# you are using. Commented Oct 21, 2010 at 2:27
  • @Esteban, I need the object because it will allow me to use the types to convert it to different formats for export. @Danny, I am using Visual Studio 2010. Commented Oct 21, 2010 at 5:35

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was not aware of the ExpandoObject.
1

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.

1 Comment

Thanks, this is very similar to what I have now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.