Question

I have set one of my properties in my base class to have a protected setter. this works fine and I am able to set the property in the constructor of the derived class - however when I try to set this property using the PropertyDescriptorCollection it will not set, however using the collection works with all other properties.

I should mention that when I rremove the protected Access modifier all works okay...but of course now it's not protected. thanks for any input.

 class base_a
{

 public  string ID { get; protected set; }
 public virtual void SetProperties(string xml){}
}

class derived_a : base_a
 {
   public derived_a()
    {
    //this works fine
     ID = "abc"
    }
   public override void SetProperties(string xml)
    {
      PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this);
      //this does not work...no value set.
      pdc["ID"].SetValue(this, "abc");

      }
  }
Was it helpful?

Solution

TypeDescriptor does not know that you call it from a type that should have access to that property setter, so the PropertyDescriptor you're using is read-only (you can verify this by checking its IsReadOnly property). And when you try to set value of a read-only PropertyDescriptor, nothing happens.

To work around that, use normal reflection:

var property = typeof(base_a).GetProperty("ID");

property.SetValue(this, "abc", null);

OTHER TIPS

Try this

PropertyInfo[] props = TypeDescriptor
    .GetReflectionType(this)
    .GetProperties();
props[0].SetValue(this, "abc", null);

Or simply

PropertyInfo[] props = this
    .GetType()
    .GetProperties();
props[0].SetValue(this, "abc", null);

(You will need a using System.Reflection;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top