I have 2 classes, Base and child class.
Base class has a protected int variable. My understanding is that any protected member of a class can only be accessed in a child class, It cannot be accessed from say creating an Instance of a class and accessing the protected member. How is this working then?
class BaseClass
{
protected int x = 0;
private static void Funny(BaseClass c, ChildClass d)
{
d.x = 9; // How can we access x here?
c.x = 0; // How can we access x here?
}
}
class ChildClass: BaseClass
{
public void MyFunc()
{
x = 0; // This should be OK, because x is a protected member of
}
private static void Funny(BaseClass c,ChildClass d)
{
d.x = 9;
c.x=0;// This is giving compile time error? According to me even above line should give compile time error
}
}
Best Answer
In C#, the scope of access modifiers is the class, not the instance. This means that a private member can be accessed within the class on any instance.
This, by the way, makes it possible (and easy) to override Equals. Otherwise, you would be limited to public properties only, which may not be exactly what you want.