KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
(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?
Tags (comma-separated)
Save Edits
Cancel