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 Virtual Properties

Patrick McLeod
Patrick McLeod
5,913 Points

Virtual Properties Challenge

Hi I´ve a question regarding this Virtual Properties Challenge that follows directly after this video. I tried it a few times and was unsuccessful until I searched for help online and noticed that the answer only works if instead of using "protected" as the public access modifier, I use "public". Why is that? Cheers, PM

1 Answer

Steven Parker
Steven Parker
231,198 Points

I answered your "piggyback" question here already.

But the "public" access allows the method to be used by any code that creates or references an instance of this class. If it were "protected", the method could only be used from inside the class itself, or a subclass created from it. This would also prevent the challenge validation mechanism from being able to access it.

Patrick McLeod
Patrick McLeod
5,913 Points

Thanks for your prompt reply. Ok, I get it but still... Considering RepeatDetector.cs is a subclass of RepeatDetector.cs, it should have worked, right? Isn't RepeatDetector.cs a subclass created from RepeatDetector.cs?

From your comment I understand that is was necessary to state "public" in order for Treamtrehouse´s validation mechanismto access it and verify the correct answer.

Steven Parker
Steven Parker
231,198 Points

It's the subclass (RepeatDetector) that the new override method is being defined in. And the method needs to be available to code that is using an instance of the subclass, so it needs "public" access.

A "protected" method would only be availble to itself and further subclasses of "RepeatDetector"