Knights, Knaves, Protected and Internal

When you override a virtual method in C# you are required to ensure that the stated accessibility of the overridden method – that is, whether it is public, internal, protected or protected internal(*) – is exactly re-stated in the overriding method. Except in one case. I refer you to section 10.6.4 of the specification, which…

42

Why Can’t I Access A Protected Member From A Derived Class? Part Six

Reader Jesse McGrew asks an excellent follow-up question to my 2005 post about why you cannot access a protected member from a derived class. (You probably want to re-read that post in order to make sense of this one.) I want to be clear in my terminology, so I’m going to define some terms. Suppose…

22

Protected Semantics, Part Five: More on immutability

I asked a second follow-up question back in Part Two: Suppose you wanted to make this hierarchy an immutable collection, where “Add” and “Remove” returned new collections rather than mutating the existing collection. How would you represent the parenting relationship? The short answer is “I wouldn’t”. First off, it sounds an awful lot like what…

5

Protected Member Access, Part Four

In Part Two I asked a couple of follow-up questions, the first of which was: Suppose you were a hostile third party and you wanted to mess up the parenting invariant. Clearly, if you are sufficiently trusted, you can always use private reflection or unsafe code to muck around with the state directly, so that’s…

1

Why Can’t I Access A Protected Member From A Derived Class, Part Three

Holy goodness, I’ve been busy. The MVP Summit was fabulous for us; thanks to all who attended and gave us great feedback on our ideas for evolving the languages and tools. And I’ve been doing some longer-lead thinking and working on language futures, which I will blog about at a later date. Last time I…

32

Why Can’t I Access A Protected Member From A Derived Class, Part Two: Why Can I?

This is a follow-up to my 2005 post on the same subject  which I believe sets a personal record for the longest time between parts of a series. (Of course, I didn’t know it was a series when I started it.) Please read the previous article in this series, as this post assumes knowledge of…

38

Why Can’t I Access A Protected Member From A Derived Class?

A question I got recently was about access to protected methods from a derived class. Clearly that’s what “protected” means – that you can access it from a derived class. In that case, why doesn’t this work? class Ungulate {  protected void Eat() { /* whatever */ }} class Giraffe : Ungulate {  public static…

9