
This is is the second entry in my series about C# keywords that trip me up.
We all know what it means to declare something public or private. If a class, method or field is marked as Public, then any other code in any other class has access to it. If we mark one as Private, then it can on;y be accessed from inside the class where it is defined.
Protected
Protected means the method can be access from the type and any derived types. Here's what will make you head explode on this one. Running WhatAmI() in this code will return "I'm a Monkey base class."
class Monkey
{
public string Talk()
{
return WhatAmI();
}
protected string WhatAmI()
{
return "I am a Monkey base class.";
}
}
class Chimp : Monkey
{
public new string Talk()
{
return WhatAmI();
}
}
Change protected string WhatAmI() to private and this won't compile unless you remove the public new string WhatAmI() from Chimp.
However, add this to Chimp and it will compile and run the private method:
private string WhatAmI()
{
return "I'm a Chimp, derived from Monkey.";
}
So the reason your brain explodes is you're overriding the protected method without either using the terms "override" or "new".
0 comments:
Post a Comment