user3312056
user3312056

Reputation: 39

C# Restrict which classes can call a method

I want to be able to restrict which classes have access to call a method of another class. I have a the following:

public class A: B
{
    private void DoSomething()
    {
        C.Method1(); // should compile
    }
}

public abstract class B
{

}

public class D
{
    private void DoSomething()
    {
        C.Method1(); // shouldn't compile
    }
}

public static class C
{
    public static void Method1()
    {

    }

    public static void Method2()
    {
       ...
       Method1();
       ...
    }

}

All of these classes are in the same assembly, but class B is in a different assembly.

My goal is for class A to be able to call C.Method1, but have class D not able to call C.Method1

I was thinking of making class C a parent class, and have class A inherit class B, but class A already inherits from class B.

Method1 doesn't belong in class A or B.

A practical use for this is when Method1 is a utility method, and should only be called by class A and class C

Upvotes: 3

Views: 1089

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56429

Without moving methods around, you'd have to make C non-static, make Method1 protected, then have B inherit from C, which would look like:

public class A : B
{
    private void DoSomething()
    {
        C.Method1(); // should compile
    }
}

public abstract class B : C
{
}

public class D
{
    private void DoSomething()
    {
        C.Method1(); // shouldn't compile
    }
}

public class C
{
    protected static void Method1()
    {
    }
}

Upvotes: 3

Related Questions