PropertyDescriptor and inheritance

861 Views Asked by At

I'm using TypeDescriptor.GetProperties(instance) and it returns me all properties and get/set methods for it from base class.

I have base class:

public class Foo
{
    public virtual string Name
    {
      get => _name;
      set => _name = value;
    }
}

Derrived class:

public class Bar : Foo
{
    public override string Name => "Test";
}

When I'm getting info for 'Name' property PropertyDescriptor.IsReadOnly equals to 'false', but it should be 'true'. How can I settup 'PropertyDescriptor' so it would return me data only for derrived class type?

1

There are 1 best solutions below

5
On

This has nothing to do with inheritance. The PropertyDescriptor object you get does describe the Bar's property.

The fact that the IsReadOnly flag is false has nothing to do with the inheritance. But rather it tells you that the property is in fact not read only.

You're maybe asking "But why?"

In your code, you're actually overriding only the get accessor of the property. The set accessor implementation is just being inherited from the base Foo class.

You can easily write something like:

Bar bar = new Bar();
bar.Name = "dummy";

This will compile and internally work too - the _name backing field will be set to the value provided.

However, this code is dangerous, since bar.Name will always return "Test" regardless of what you set via bar.Name = "string value here". Furthermore , this code breaks the Liskov substitution principle, because the behavior of the child class Bar is different than the one stated by the public interface of the base class Foo.

A read only property means that you cannot set it's value, so the compiler wouldn't even allow you to write bar.Name = "text". But it does allow you to do that. The property in your case is not read only, it has a buggy (broken) implementation.