Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 855
Nelson Rothermel Avatar asked Dec 09 '10 22:12

Nelson Rothermel


People also ask

How do you set a readonly property in TypeScript?

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.

Can property be readonly in C#?

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#.

Can readonly property be set in constructor?

You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.


1 Answers

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

like image 180
JaredPar Avatar answered Oct 15 '22 22:10

JaredPar