Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to make a method only visible to classes that inherit the base class of the method

I have a base class that is marked as abstract. Is it possible to make a method in that base class only visible to other classes that are inheriting the base class?

Say I have Class1 that is my base class and is marked as abstract. Class2 Inherits Class1 and can make calls to all of it's public methods. I want Class3 to create an instance of Class2 but not be able to make calls to certain methods of Class1. I tried marking these methods as abstract themselves but then I get an error when Class2 tries to use them. The error is: "...Cannot declare a body because it is marked as abstract"

like image 389
PICyourBrain Avatar asked Nov 16 '10 17:11

PICyourBrain


1 Answers

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
    }
}
like image 195
George Stocker Avatar answered Oct 23 '22 11:10

George Stocker