Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit method to only be called by a particular class

Tags:

c#

I want a particular method in one class to only be accessible by a particular class. For example:

public class A {   public void LimitedAccess() {}   public void FullAccess() {} }  public class B {   public void Func()   {      A a = new A();      a.LimitedAccess();       // want to be able to call this only from class B   } }   public class C {   public void Func()   {      A a = new A();      a.FullAccess();           // want to be able to call this method      a.LimitedAccess();        // but want this to fail compile   } }  

Is there is a keyword or attribute that I can use to enforce this?

UPDATE:

Due to existing system complexity and time constraints, I needed a low impact solution. And I wanted something to indicate at compile time that LimitedAccess() could not be used. I trust Jon Skeet's answer that exactly what I had asked for could not be done in C#.

The question and Jon's answer are good for those who may run across this later. And the fact that this design smells can hopefully veer anyone away for choosing something like this as a desired a solution.

As mentioned in a comment, the C# friend conversation is useful reading if you are trying to solve a similar situation.

As for my particular solution: "why would A contain B's logic" (asked by @sysexpand in comments). That's the rub. B.Func() was called throughout the system I'm working on, but it primarily operated on a singleton of A. So what I ended up doing was moving B's Func() into A and making A.LimitedAccess() private. There were a few other details to work around, as there always are, but I got a low impact solution that gave me compile-time errors on callers to A.LimitedAccess().

Thanks for the discussion.

like image 973
jltrem Avatar asked May 15 '13 18:05

jltrem


People also ask

How do you limit access to a method of a public class to members of the same class?

Explanation: The private access modifier limits access to members of the same class.


1 Answers

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.)

like image 112
Jon Skeet Avatar answered Sep 21 '22 08:09

Jon Skeet