‘protected internal’ != (‘protected’ & ‘internal’)
By rickvdbosch
- 2 minutes read - 234 wordsHaving a database management class called DatabaseManager, I wanted to make a property for this DatabaseManager in a BaseForm. This way, every form inheriting from BaseForm would be able to use the same instance of the DatabaseManager.
Because the DatabaseManager exposes functionality to interact with the database, I wanted it to be internal. The property for the DatabaseManager in the BaseForm would have to be internal and protected, so only derived forms would be able to use the property. And exactly there is where I had wrong expectations about what the .NET framework delivers, resulting in the error “Inconsistent accessibility: property type ‘x’ is less accessible than property ‘y’.”
Defining a property to be ‘protected internal‘ makes the property visible for internal classes OR classes which inherit from that class. And it’s actually pretty straight forward: the BaseForm was still public (default), making it inheritable for classes outside of the current assembly. Marking a property as ‘protected’ makes sure inheriting classes are able to see that property. And so ‘protected internal’ is protected OR internal, not AND.
When you think about it the solution is as straight forward as the behaviour of the accessibility modifiers. The BaseForm should be internal, and the property should be protected. This way, no one is able to inherit from the BaseForm from outside the assembly. Inside the assembly, only BaseForm-inheriting forms are able to see the DatabaseManager property.