Lorago
Lorago

Reputation: 161

Prevent inherited member from accessing protected member

Is there a way in C# to prevent a derived class from inheriting a protected property?

class Base
{
   protected int A { get; set; }
}

class DerivedA : Base
{
}

class DerivedB : DerivedA
{
}

What I want is for DerivedA to be able to access property A, however DerivedB should not. So is there a way to limit the inheritance of a property in the middle of the inheritance hierarcy?

Upvotes: 3

Views: 477

Answers (3)

Zohar Peled
Zohar Peled

Reputation: 82534

Well, there is some valuable information in the comments, so I thought I'd better recap it so it will not get lost.

Kevin Gosse suggested to use the private protected access modifier.

The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.

Please note that this access modifier is only available in c# 7.2 or higher.

While I agree with Kevin this might be a direct answer to your question, HimBromBeere suggested that this question is, in fact, an XYProblem - meaning you are asking how to implement a solution you are having problems with, instead of asking how to solve the underlying problem.
I also agree with him as well.

Fildor suggested using composition over inheritance - which is a very good point. using inheritance only for code reuse is a mistake. Remember that a derived class is a specific type of the base class type - for instance, a dog can derive from animal because a dog is a specific type of animal, but an airplane can't derive from a car just because they both have engines.

To get an answer to the actual underlying problem, I suggest you edit your question to include that problem, not only the current solution you are trying to implement, or perhaps ask a brand new question instead.

Upvotes: 3

kaffekopp
kaffekopp

Reputation: 2619

Why would you want a class to not inheriting a protected property of its base class? You should redesign your class model:

    class Base
    {            
    }

    class BaseA : Base
    {
        protected int A { get; set; }
    }

    class Derived : Base
    {
    }

    class DerivedA : BaseA
    {
    }

Upvotes: 0

roozbeh S
roozbeh S

Reputation: 1124

You should make it sealed:

class Base
{
   protected int A { get; set; }
}

class DerivedA : Base
{
   protected sealed override int A { get => base.A; set => base.A = value; }
}

class DerivedB : DerivedA
{
   // Attempting to override A causes compiler error.
}

read more here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed

Upvotes: 1

Related Questions