Search code examples
c#reflectiongetproperty

(C#) How to store value based on the name field?


I have a ArrayList with names of a fields in the current object, when i try to do this:

foreach(string name in array)
{
  PropertyInfo property =  this.GetType().GetProperty(name);
  property.SetValue(this, value , null);
}

The execute is failed, and the property has no value (in SharpDevelop only says "null"). The names of the fields are OK and exists, whats happens?


Solution

  • Does your property has a setter (set accessor). better check that before setting the property like

    if(property != null && property.CanWrite)
    {
        property.SetValue(this, value , null);
    }
    

    BTW, is it a field or property you are trying to access? since you said The names of the fields are OK and exists