Generically creating objects in C#

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.

Answers


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.


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


Activator.CreateInstance


Need Your Help

PHPUnit Database - no such table

php phpunit

I am trying to run very simple PHPUnit testing class with Database simulation. I am trying to create dataset with some values. I am using MySQL XML object.

Problem with accessing in DOM with jQuery

jquery json dom callback jsonp

I changed the tree of my JSON-P output, and i cannot access to my object DOM anymore :