C# - How to make a method only visible to classes that inherit the base class of the method
Why not declare the method protected
?
public abstract class Class1
{
protected abstract void Method1();
public abstract void Method2();
}
public class Class2 : Class1
{
protected override void Method1()
{
//Class3 cannot call this.
}
public override void Method2()
{
//class 3 can call this.
}
}
public class Class3
{
public void Method()
{
Class2 c2 = new Class2();
c2.Method1(); //Won't work
c2.Method2(); //will work
}
}
It sounds like you're looking for the protected
keyword. This limits the member tagged with protected
for use only for the declaring type or types which derive from that type.
abstract class Class1 {
protected void Method1() {
...
}
}
class Class2 : Class1 {
public void Method2() {
Method1(); // Legal
}
}
class Class3 {
public void Example() {
Class2 local = new Class2();
local.Method2(); // Legal
local.Method1(); // Illegal since Method1 is protected
}
}
You need to mark them in both Class1 and Class2 as protected
. This access modifier allows derived class(es) access to a member, but nothing outside the derived class(es) can see it.