limit method to only be called by a particular class

Yes. What you are asking for is perfectly possible.

You can restrict access to methods and variables for a specific instance, by using an interface.

However, an interface alone cannot prevent someone from creating their own instance of the class, at which point they will have full access to that instance.

To do that, next you should nest it as a private class inside of another class in order to restrict access to the constructor.

Now you have a particular method in one class to only be accessible by a particular class.

In this example, only class B is ever able to access function LimitedAccess.

public interface IA
{
  void FullAccess();
}

public class B
{
  private class A : IA
  {
    public void LimitedAccess() {}  //does not implement any interface
    public void FullAccess() {}     //implements interface
  } 
    
  private A a = new A();

  public IA GetA()
  {
    return (IA)a;
  }
  
  public void Func()
  {
     /* will be able to call LimitedAccess only from class B, 
        as long as everybody else only has a reference to the interface (IA). */
     a.LimitedAccess();       
  }
} 


//This represents all other classes
public class C
{  
  public void Func(IA ia)
  {
     ia.FullAccess();           // will be able to call this method
     ia.LimitedAccess();        // this will fail to compile
  }
} 

public static class MainClass
{
  public static void Main(string[] args)
  {
    B b = new B();
    b.Func();
          
    IA ia = b.GetA();
      
    C c = new C();
    c.Func(ia);
  }
}

No. The only thing you could do would be to make LimitedAccess a private method, and nest class B within class A.

(I'm assuming you want all the classes in the same assembly. Otherwise you could put A and B in the same assembly, and C in a different assembly, and make LimitedAccess an internal method.)

Tags:

C#