(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 the Fox
class instance in RedFox
? RedFox
is derived from Fox
, 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 the RedFox
class instance. So, why can't I expect the same from the Fox
class instance?
Simple reason is:
public void IncorrectPaintFox(Fox anotherFox)
{
anotherFox = new BlueFox();
// This one is inaccessible here and results in a compilation error.
anotherFox.FurColor = "Hey!";
}
Now you're not accessing the protected field from within BlueFox
, therefore since the compiler doesn't know what the runtime type is, it has to always make this an error.