Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# Polymorphism Accessor Access Modifiers

evanpavan
evanpavan
5,025 Points

Why can't you override fields?

As per the other question asked, I understand that we changed the constant fields on the Invader class to properties.

But why can't you override class members that are fields? What's the logic behind that in terms of C#?

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

You can reassign a property to something else without needing the override keyword. Is this what you're referring to? Are you asking why we don't need to explicitly use the override keyword? Or is there some behavior you want that you're not able to get out of the C# language?

2 Answers

I think one reason is that override is for methods, which properties have (as accessors) and fields don't, so methods can extend overridden methods from base classes by calling them through the base object. Would we ever extend field values or just replace them? Redefining the field without override, however, only hides the inherited field, which means it still gets accessed in ways the programmer may not want, unless access were controlled through properties. Language design is filled with arbitrary choices that aren't necessarily logical. The language designers may have felt fields should focus on binding data to class instances, and properties should focus on directing access (including overrides).

Fields are intrinsically private and properties are public. You can only access properties outside of the immediate class and override them. Since fields are private and can't be accessed outside of the class they were declared in, there is no way to override them.