Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected Access for Instance Members in C#? [duplicate]

Tags:

c#

.net

protected

Possible Duplicate:
Why can’t I access C# protected members except like this?

As I was reading a c# book (special annotated version which shows all the tricky part of c#)

I saw this code :

public class A
{
    protected int x;
    static void F(A a, B b)
    {
        a.x = 1; // Okay
        b.x = 1; // Okay
    }
}
public class B: A
{
    static void F(A a, B b)
    {
        a.x = 1; // Error: must access through instance of B
        b.x = 1; // Okay
    }
}

looking at protected meanning :

Access limited to this class or classes derived from this class

Questions

  • Why does this restriction (via instances) exists ?

  • Can you please supply an example of a problematic situation as if it was allowed ?

like image 247
Royi Namir Avatar asked Feb 18 '26 13:02

Royi Namir


1 Answers

Your quoted meaning of protected is not the technical definition, but merely what the spec quotes as the intuitive meaning (section 3.5.1):

The intuitive meaning of protected is “access limited to the containing class or types derived from the containing class”.

Further down in the same section it gives a more rigorous definition (Here M is member of a type T):

Otherwise, if M is protected, the access is permitted if it occurs within the class in which M is declared, or if it occurs within a class derived from the class in which M is declared and takes place through the derived class type (§3.5.3).

The referenced section (3.5.3) is specifically about protected member access and contains your example with the note:

This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

Thus the answer is clear. It is designed to prevent a third class from doing something like this:

public class C : A
{
  public static void F(A a, B b, C c)
  {
     a.x = 1; // not allowed
     b.x = 1; // not allowed
     c.x = 1; // allowed
  }
}

With your definition of protected the first two assignments would be allowed. This would be rather odd. Say I had my library and I defined A and B but I let you inherit from A and you wrote C. I would be a little alarmed as a library author that some one could modify the internal details in instances of classes that I wrote! Sure you could expose modification of the field x in C through a property or method but that behavior is limited to instances of your class C.

like image 137
Mike Zboray Avatar answered Feb 20 '26 02:02

Mike Zboray