On a recent .NET project I was defining an abstract class in C# when I came upon a unusual case: I needed a property that had an abstract getter, but a concrete setter. In other words, the getter needed to be implemented by all derived classes and the setter does not, in fact its defined in the abstract class. Nothing I like more than a good object oriented programming quandry.
Here’s some code to help make sense of it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
While the above syntax will generate a compile time error, there is a fairly simple way to work around the issue. Check out this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Here we delegated the setting and getting of the property to separate protected methods within BaseClass. Now that 2 methods are used we can assign whether or not they are abstract separately. The getter must be implemented by the derived classes, the setter may or may not be.
And that’s it. Obviously this code also works vice versa, with the setter being abstract and the getter being concrete. It’s nice because from the perspective of someone using your code, nothing changes with regards to the public Value property. The use of protected methods to defer overriding and abstraction help you avoid writing any unnecessarily redundant code in your derived classes. It’s a nice little trick to have in your pocket.
Happy C# OOP’ing!