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
PropertyDescriptor
object you get does describe theBar
's property.The fact that the
IsReadOnly
flag isfalse
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. Theset
accessor implementation is just being inherited from the baseFoo
class.You can easily write something like:
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 viabar.Name = "string value here"
. Furthermore , this code breaks the Liskov substitution principle, because the behavior of the child classBar
is 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.