MilitaryG
MilitaryG

Reputation: 75

how to make that only certain class can access a class

What I want to do is forbidding SomeRandom class accessing Protected class

public class CertainClass {
    public void CerFunc(){
        ProtectedClass.ProtectedFunction();
    }
}
public class ProtectedClass {
    public static void ProtectedFunction(){
        Debug.Log("Protected");
    }
}
public class SomeRandomClass {
    public void RandFunc(){
        ProtectedClass.ProtectedFunction(); // innaccessible due to protection level
    }
}

what do I have to change in order to make that work?

Preferably Static, because I need and want it only 1.

Upvotes: 0

Views: 905

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81243

Make it private nested class of CertainClass:

public class CertainClass
{
    private class ProtectedClass
    {
        public static void ProtectedFunction()
        {
            Debug.Log("Protected");
        }
    }
    public void CerFunc()
    {
        ProtectedClass.ProtectedFunction();
    }
}

UPDATE

If you want another CertainClass2 to access your ProtectedClass members -

Either make CertainClass2 as public nested class of CertainClass.

OR

I would suggest to move ProtectedClass and other classes which want to access it into another assembly and make ProtectedClass as internal so that all classes in that assembly can have access to this class and it is invisible to other classes outside this assembly.

Upvotes: 1

Related Questions