Search code examples
c#propertiesoverridingaccess-modifiers

Make property readonly in derived class


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 { }?


Solution

  • 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