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!
privateis scoped to the class, not instances.