This is a mirror of official site: http://jasper-net.blogspot.com/

Hide and seek

| Wednesday, June 16, 2010
Another interesting question from StackOverflow. That thing is a gold mine for blog topics. Consider the following:

class B
{
 public int X() { return 123; }
}
class D : B
{
 new protected int X() { return 456; }
}
class E : D
{
 public int Y() { return X(); } // returns 456
}
class P
{
 public static void Main()
 {
   D d = new D();
   Console.WriteLine(d.X());
 }
}

There are two possible behaviours here. We could resolve X to be B.X and compile successfully, or resolve X to be D.X and give a "you can't access a protected method of D from inside class Program" error.

[UPDATE: I've clarified this portion of the text to address questions from the comments. Thanks for the good questions.]

We do the former.To compute the set of possible resolutions of name lookup,  the spec says"the set consists of all accessible members named N in T, including inherited members" but D.X is not accessible from outside of D; it's protected. So D.X is not in the accessible set.

The spec then says "members that are hidden by other members are removed from the set". Is B.X hidden by anything? It certainly appears to be hidden by D.X. Well, let's check. The spec says "A declaration of a new member hides an inherited member only within the scope of the new member." The declaration of D.X is only hiding B.X within its scope: the body of D and the bodies of declarations of types derived from D. Since P is neither of those, D.X is not hiding B.X there, so B.X is visible, so that's the one we choose.

Inside E, D.X is accessible and hides B.X, so D.X is in the set and B.X is not.

Read more: Fabulous Adventures In Coding

Posted via email from .NET Info

0 comments: