The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««May 2008»»
SMTWTFS
     123
45678910
11
12
13
14
15
1617
18192021222324
25262728293031

My Top Tags

                                       

Mailing List

My RSS Feeds








Create an object dynamically with CreateInstance using Reflection

posted Friday, 7 December 2007

You can instantiate an object dynamically using Reflection. For example, the boards in TruckWars are stored in Xml files. Each board has a list of creatures:

 

  <Creatures>
    <Creature type="TankUnit" boardPosition="1.5, 7.5" team="Hero" />
    <Creature type="PickupTruck" boardPosition="1.5, 2" team="Hero" />
    <Creature type="PushButtonStayDown" boardPosition="13.5, 1.5" />
    <Creature type="TankUnitEnemy" boardPosition="14.2, 7.5" team="Enemy1" />
  </Creatures
>

 

You could use an xml reader to cycle through this, and at each creature node, dynamically create a creature object. The "trick" is to have a base type (like "CreatureBase") that all your objects inherit from. You then specify the type in the xml file, and use the CreateInstance() method to dynamically create an object (to my knowledge, this requires that the base type at least have an empty constructor):

 

        CreatureBase c = (CreatureBase)Assembly.GetExecutingAssembly().CreateInstance(CreatureNamespace + "." + strType);
        c.Position = strPositionSerializedFromXmlAttribute;
        c.Team = (Team)Enum.Parse(typeof(Team), strTeam, true);    //makes an enum
        c.Name = strName;

 

You can then serialize the xmlNode's attributes and use them to set properties on that object. Thanks to polymorphism, the object will act as the derived type (for example, it will call the derived type's overridden methods).

 

This technique is often used in enterprise architecture for extensibility. The core system creates the base class, but then you can override it and set some xml config file to use your derived type.

 

tags:  

links: digg this    technorati