Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Restrict which classes can call a method

Tags:

c#

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

like image 296
user3312056 Avatar asked Mar 15 '26 07:03

user3312056


1 Answers

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()
    {
    }
}
like image 139
mattytommo Avatar answered Mar 16 '26 21:03

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!