tags:

views:

136

answers:

3

What I am trying to do is load in objects from an XML save file. The problem is those objects are configurable by the user at runtime, meaning i had to use reflection to get the names and attributes of those objects stored in an XML file.

I am in the middle of a recursive loop through the XML and up to the part where I need to create an object then thought ..... ah - no idea how to do that :(

I have an array stuffed with empty objects (m_MenuDataTypes), one of each possible type. My recursive loading function looks like this

private void LoadMenuData(XmlNode menuDataNode)
{
   foreach (object menuDataObject in m_MenuDataTypes)
   {
       Type menuDataObjectType = menuDataObject.GetType();
       if (menuDataObjectType.Name == menuDataNode.Name)
       {
          //create object
       }
   }
}

I need to put some code where my comment is but I can't have a big switch statement or anything. The objects in my array can change depending on how the user has configured the app.

+12  A: 

You want to use Activator.CreateInstance(Type)

object instance = Activator.CreateInstance(menuDataObjectType);

for this to work efficiently, you may need to restrict the dynamically created instances to implement an interface

ICommonInterface i = (ICommonInterface)Activator.CreateInstance(menuDataObjectType)

That way, the dynamically created object becomes usable - you can call interface methods on it.

Marek
if the activator returns a type of "object" is it parseable to its actual type? For example, if I just stuffed it in an ArrayList could i do something like if(object[4] is TurboButton)?
DrLazer
The object returned is an instance of the type that you passed to CreateInstance. You can cast it back to your type. (or use the is operator, etc). there are several overloads of CreateInstance that you should look at -- including one that accepts a string type name and a string assembly name.
JMarsch
nice one will do
DrLazer
here have a tick marek
DrLazer
+1  A: 

Activator.CreateInstance

Timbo
+2  A: 

If you're instantiating a graph of objects, would the XmlSerializer or DataContractSerializer be more appropriate?

Damian Powell
Yeah its a nice idea - I have a requirement for it to be easily human readable though :'(
DrLazer
No reason why it shouldn't be neat and tidy if you specify enough detail in the attributes on your classes.
Damian Powell
plus there is already a load of other functionality in the app that deals with those XML files being worked on by other peeps - you know the crack. if it was up to me we would save it as encrypted gash
DrLazer
"encrypted gash" - lol
Damian Powell