athos
athos

Reputation: 6405

C#: access right due to inheritance

Below is a simple testing code:

public class A
{
    protected int m = 0;
}

internal class B: A
{
    public void test(A objA, B objB)
    {
        base.m++; //OK!
        objA.m++; //cannot access protected member

        m++;      //OK!
        objB.m++; //OK!
    }
}

May I ask, why in method B.testA(), it's OK to access base.m (here base is class A), but cannot access objA.m?

Upvotes: 1

Views: 136

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

That's how the protected modifier is implemented. You can access it from the class itself or derived classes but you cannot access it if you have an instance of the object. You will have to make it public if you want it to be accessible given an instance of the class. Another possibility is to make it protected internal meaning that it will be public for all types within the current assembly and protected for types in other assemblies.

Upvotes: 5

Related Questions