1

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.

K. Dobson
  • 11
  • 1
  • Could you use a dictionary instead? Dictionary itemLookup itemLookup[whichCItem].addPropertyToList – Brian Sep 21 '18 at 17:16

2 Answers2

0

A simple Dictionary<T, U> might work for you. Consider an example:

CItems me = new CItems();
CItems conversations = new CItems();
... 
var dic = new Dictionary<string, CITems>();
doc.Add("me", me); 
doc.Add("conversations", conversations);
... 

//find object 
CITems result= null; 
dic.TryGetValue(searchString, out result);
Tigran
  • 61,654
  • 8
  • 86
  • 123
0
PropertyInfo property = myobject.GetType().GetProperty(propertyname);

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

var propertyInfo = CItems.GetProperty(propertyname)

to retrieve the class property. What you now need to do is set that property on the identified instance, so that you can call

propertyInfo.SetValue(<instance>, value);

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?

IEnumerable<CItems> myItems = new { new CItem("me"), new CItem("conversations") }


void somemethod(string instanceName, string propertyname)
{
    var instance = myItems.FirstOrDefault(item => item.Name == instanceName);
    if(instance == null) return;

    var propertyInfo = CItems.GetProperty(propertyname);
    propertyInfo.SetValue(instance, value);
}