Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generically creating objects in C#

Tags:

c#

reflection

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.

like image 376
DrLazer Avatar asked Apr 19 '10 14:04

DrLazer


1 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.

like image 93
Marek Avatar answered Sep 19 '22 10:09

Marek