I'm overriding a property in my derived class that I would like to make it readonly. The C# compiler won't let me change the access modifiers, so it must stay public.
What's the best way to do this? Should I just throw an InvalidOperationException
in set { }
?
Creating Read-Only Properties in TypeScript To create a read-only property, we prefix the keyword readonly before the property name. In the example below the price property is marked as readonly . We can assign a value to the price property when we initialize the object. However, we cannot change its value afterward.
C# ReadOnly Property FeaturesIn c#, we can create the Read-only fields using readonly keyword. In c#, you can initialize the readonly fields either at the declaration or in a constructor. The readonly field values will evaluate during the run time in c#.
You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.
Having the setter throw an InvalidOperationException
in a derived class violates the Liskov Subsitution Principle. Essentially makes the usage of the setter contextual to the type of the base class which essentially eliminates the value of polymorphism.
Your derived class must respect the contract of it's base class. If the setter is not appropriate in all circumstances then it doesn't belong on the base class.
One way to work around this is to break the hierarchy up a little bit.
class C1 {
public virtual int ReadOnlyProperty { get; }
}
class C2 {
public sealed override int ReadOnlyProperty {
get { return Property; }
}
public int Property {
get { ... }
set { ... }
}
}
Your type you're having problems with could inherit C1
in this scenario and the rest could switch to derive from C2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With