vendredi 21 septembre 2018

C# Using reflection to get a an instantiated class given a string variable containing its name

In C# I have multiple instantiations of a class "CItems"(see below). I retrieve a string at run-time of the instantiation I want to use(in this case to call a public method-"addPropertyToList"). I know I have to use reflection but I can't seem to get it right.

CItems me = new CItems();
CItems conversations = new CItems();

string whichCItem = "me"

properties = <whichCItem>.addPropertyToList(properties, "FirstName", "Ken");

I tried many things like:

var myobject = this;
string propertyname = "me";
PropertyInfo property = myobject.GetType().GetProperty(propertyname);
object value = property.GetValue(myobject, null);

But that resulted in: Object reference not set to an instance of an object. Because property ends up null.

Thanks for any help and please be gentle. I really have no idea what I am doing and I may have used some wrong terminology.





Aucun commentaire:

Enregistrer un commentaire