2

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?

manhattan
  • 133
  • 2
  • 10
  • 1
    Just curious - is this a school assignment? Not saying that's bad if it is. But I've noticed that education materials use `ArrayList` even though they haven't been common since we got generics in 2005. – Scott Hannen Aug 07 '16 at 01:38
  • 1
    The best would be to provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). It will be very easy to answer then. – sstan Aug 07 '16 at 03:34
  • I'm a begginer with c#, i try to make a Active Record, with this method i wish load the tuple to the object instante. Jaja no problem! – manhattan Aug 07 '16 at 03:58
  • You say you want to set values of fields, but your code sets values of properties. Which is it? How are these "fields" declared? When failing to retrieve type members, things to double check include the name, the kind of the member (e.g. property vs field), and binding flags (e.g. static vs non-static, public vs private, etc.). Please provide a good [mcve] that reliably reproduces your problem. The question would be trivial to answer with a halfway decent code example. – Peter Duniho Aug 07 '16 at 05:26

1 Answers1

0

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

Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Thanks! i only make attributes without setter and getter accesors, Now i find a way to get the property name string... thanks again – manhattan Aug 09 '16 at 03:41