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?
This has nothing to do with inheritance. The
PropertyDescriptorobject you get does describe theBar's property.The fact that the
IsReadOnlyflag isfalsehas 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
getaccessor of the property. Thesetaccessor implementation is just being inherited from the baseFooclass.You can easily write something like:
This will compile and internally work too - the
_namebacking field will be set to the value provided.However, this code is dangerous, since
bar.Namewill always return"Test"regardless of what you set viabar.Name = "string value here". Furthermore , this code breaks the Liskov substitution principle, because the behavior of the child classBaris different than the one stated by the public interface of the base classFoo.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.