0

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Pim Dröge
  • 85
  • 1
  • 10
  • Do all of the classes have the same members? Why not give them all a common ancestor? – Steve Jun 25 '13 at 20:28
  • @Steve: No they don't I just created these classes in the example as easy as possible although the classes of CRM 4.0 are all completely different with different members. – Pim Dröge Jun 25 '13 at 20:30
  • I would think you could definitely do this using reflection, but it's not something I've worked with very much. See http://stackoverflow.com/a/9458673/425871 which has some information on the topic. – Steve Jun 25 '13 at 20:33
  • @Steve Thanks. I will have a look at that. – Pim Dröge Jun 25 '13 at 20:37
  • 1
    Seems like naming a class 'class' is going to cause problems all by itself. – Meredith Poor Jun 25 '13 at 20:41
  • @MeredithPoor This was just an example in the program itself there are no classes named `class` – Pim Dröge Jun 25 '13 at 20:44

1 Answers1

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

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

Community
  • 1
  • 1
catfood
  • 4,267
  • 5
  • 29
  • 55
  • This would work if i knew what class it was although at the point of creating the instance with Activator i only have a string name of the class. Therefor doing (foo as test) won't be possible cause at that point i don't know its the class test yet. – Pim Dröge Jun 25 '13 at 20:35
  • I was trying to draw that information out of you. You didn't give the context of where the activation would be happening. :-) – catfood Jun 25 '13 at 21:37