Dynamically create instance of class which can be different each time and still be able to access it's properties

StackOverflow https://stackoverflow.com/questions/17306793

Question

I'm trying to achieve the following:

I have for example 3 custom classes named class, test and unknown as followed:

public class class
{
  public string name { get; set; }
  public Guid ID { get; set; }
  public int interval { get; set; }
}

public class test
{
  public string name { get; set; }
  public Guid ID { get; set; }
  public int interval { get; set; }
}

public class unknown
{
  public string name { get; set; }
  public Guid ID { get; set; }
  public int interval { get; set; }
}

Now in my program i read an XML file which contains lines with the name of the class it has to create an instance of.

<Messages>
  <Message Name='ClassMessage' Type='class' />
  <Message Name='TestMessage' Type='test' />
  <Message Name='UnknownMessage' Type='unknown' />
</Messages>

I will loop through each line in the XML and based on the given type in the XML i have to create an instance of that class. I know you can achieve this with Activator.CreateInstance() only problem is, that i won't be able to access it's properties (name, ID, interval).

In the above example it's about only 3 classes although i'm working on something that talks against the webservice of Microsoft Dynamics CRM 4.0 and that has alot more classes which it should be able to choose from.

Was it helpful?

Solution

object foo = Activator.CreateInstance("test");
(foo as test).name = "TestMessage";

Update: This is what you really want to do. Set object property using reflection

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top