4

I wonder why the following is allowed in C#:

When I define a class MyClass with a private method. Lets calls its instance A. Now I create an instance of MyClass in one of its public methods. This instance is called B. So B is an instance in A both of the same type.

I can call this private method on B from A. To me the method is private meaning only B can call it itself and no other class. Apparently, another class of the same type can also call it on B.

Why is this? It has to do with the exact meaning of the private keyword?

Code example:

public class MyClass
{
    private static int _instanceCounter = 0;

    public MyClass()
    {
        _instanceCounter++;
        Console.WriteLine("Created instance of MyClass: " + _instanceCounter.ToString());
    }

    private void MyPrivateMethod()
    {
        Console.WriteLine("Call to MyPrivateMethod: " + _instanceCounter.ToString());
    }

    public MyClass PublicMethodCreatingB()
    {
        Console.WriteLine("Start call to PublicMethodCreatingB: " + _instanceCounter.ToString());
        MyClass B = new MyClass();
        B.MyPrivateMethod(); // => ** Why is this allowed? **
        return B;
    }
}

Thank you!

3
  • 1
    private is scoped to the class, not instances. Commented Mar 21, 2017 at 10:06
  • As you say, no other class! B is of type MyClass and you have access to it's private members inside MyClass. That's very simple. Commented Mar 21, 2017 at 10:32
  • Thank you, it is clear now! Commented Mar 22, 2017 at 19:51

1 Answer 1

6

B.MyPrivateMethod(); is allowed because the method is being called within a method in the MyClass class.

You would not be able to call MyPrivateMethod() outside of methods in the MyClass class, however because PublicMethodCreatingB is in the same class, all private methods and variables are accessible to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it helpt me out!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.