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.
This is the correct approach for tretrieving the property identified by propertyname. You already know the type it is declared on, so you just use
to retrieve the class property. What you now need to do is set that property on the identified instance, so that you can call
How are your instances identified? Surely you are not giving back the name of the variable in which the object pointer is stored?
Is something like the following achievable?