(This question is a follow-up to C# accessing protected member in derived class)
I have the following code snippet:
public class Fox
{
protected string FurColor;
private string furType;
public void PaintFox(Fox anotherFox)
{
anotherFox.FurColor = "Hey!";
anotherFox.furType = "Hey!";
}
}
public class RedFox : Fox
{
public void IncorrectPaintFox(Fox anotherFox)
{
// This one is inaccessible here and results in a compilation error.
anotherFox.FurColor = "Hey!";
}
public void CorrectPaintFox(RedFox anotherFox)
{
// This is perfectly valid.
anotherFox.FurColor = "Hey!";
}
}
Now, we know that private and protected fields are private and protected for type, not instance.
We also know that access modifiers should work at compile time.
So, here is the question - why can't I access the
FurColor
field of theFox
class instance inRedFox
?RedFox
is derived fromFox
, so the compiler knows it has access to the corresponding protected fields.Also, as you can see in
CorrectPaintFox
, I can access the protected field of theRedFox
class instance. So, why can't I expect the same from theFox
class instance?