C# – How C# Protected Access Modifier Works When Applied to a Member Variable

access-modifiersc

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.

public class Price
{
    private int amount;

    private static void CheckAmountOf(Price price)
    {
        // The following line is possible, even if `amount` is private and we are accessing an
        // instance of the object which was passed by a parameter.
        if (price.amount < 0)
        {
            throw new InvalidValueException("The price cannot be negative.");
        }
    }
}

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.

class Price
{
    private int amount;

    public override bool Equals(object obj)
    {
        ...
        var price = obj as Price;
        ...
        // The next line is valid, even if `amount` is private and even if the initial argument
        // was of type `object`. This way, you don't need to have a corresponding `Amount`
        // property with a public getter.
        return this.amount == price.amount;
    }
}