Why can I call a private method on a different instance than myself

I wonder why the following is allowed in C #:

When I define a class MyClass

with a private method. Lets name its instance A

. Now I create an instance MyClass

in one of my public methods. This instance is called B

. So, B

there is also an instance in A

both of the same type.

I can call this private method on B

from A

. For me, a method is a private value, B

or no other class can name it. Apparently another class of the same type might also call it B

.

Why is this? Does this have to do with the exact meaning of the private keyword?

Sample code:

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!

+3


source to share


1 answer


B.MyPrivateMethod();

allowed because the method is called inside a method in the class MyClass

.

You will not be able to call MyPrivateMethod()

outside of methods in the class, MyClass

however, since it PublicMethodCreatingB

is in the same class, all private methods and variables are available to it.



+5


source







All Articles