Search code examples
c#inheritancepropertiesstylecop

Protected Variables for Inheritance (StyleCop SA1401)


So I'm fixing all of our code via StyleCop rules and one that I'm hitting a lot is SA1401 FieldsMustBePrivate. I understand it and we've been really good at implementing it . . . sort of. One thing that we've always done is make our variables protected AND provide properties. This is so that classes that inherit from the base class can access the variables themselves, but classes outside of the inheritance chain have to access the values via properties.

I find this particularly useful in a case where the base class needs to set the value of a variable in an inherited class without providing a setter on the property so that classes outside of the inheritance chain cannot modify the value. What I'm finding by "fixing" SA1401 issues is that I'm opening up property values to be set, because I need to set them in their inherited class, that I really don't want to be settable.

I suppose I could just create a protected property on the base class that allows me to set the value and then create a "new" public property that does not allow me to set the value, but then I have to create that "new" public property on every inherited class.

Thoughts?


Solution

  • Can't you do both at the same time:

    public SomeType SomeProperty { get; protected set; }
    

    The property is then gettable publicly, but only settable by the class and its sub-classes.