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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With