How can I access a protected member from a derived class?

First I encountered the error message:

Compiler Error CS1540: Cannot access protected member 'member' via a qualifier
of type 'type1'; the qualifier must be of type 'type2' (or derived from it).

Then I encountered Eric Lipperts explanation of Why Can’t I Access A Protected Member From A Derived Class?

Then I got angry. And then, after working my emotions I had to figure out a solution.

Lets start with the example provided by Mr. Lippert:

class Ungulate {
  protected void Eat() { /* whatever */ }
}

class Giraffe : Ungulate {
  public static void FeedThem() {
    Giraffe g1 = new Giraffe();
    Ungulate g2 = new Giraffe();
    g1.Eat(); // fine
    g2.Eat(); // compile-time error “Cannot access protected member”
  }
}

The problem here is that the compiler won’t let you touch g2.Eat() from within the context of Giraffe, simply because all that the compiler knows is that g2 is (or is derived from) an Ungulate. The compiler couldn’t care less whether or not Giraffe is derived from Ungilate itself. That is protection and - according to the responsible ones - by design.

Anyway, I had to figure a way around. My goal was to ensure future access to the protected method from any derived class. And what was my solution? To add a protected dispatch wrapper (in this case static) around my protected method:

class Ungulate {
  protected void Eat() { /* whatever */ }
  protected static void Eat(Ungulate instance) {
    instance.Eat();
  }
}

class Giraffe : Ungulate {
  public static void FeedThem() {
    Giraffe g1 = new Giraffe();
    Ungulate g2 = new Giraffe();
    g1.Eat(); // fine
    Ungulate.Eat(g2);  // fine aswell
  }
}

Breaking some principles of encapsulation? Maybe, but it works like a charm ;)

-petter

Leave a comment...

Powered by WordPress. Entries (RSS) and Comments (RSS).