Make the Name virtual property in the base class Person . In the Spy derived class, override the property and throw Exception in getter.
public class Person { public virtual string Name { get; set; } } public class Spy : Person { public override string Name { get { throw new Exception("You never ask for a spy name!"); } set { base.Name = value; } } }
But instead of throwing an exception, I would suggest something like
get { return "**********"; }
Because it breaks the LSP (mentioned in another answer). What does this mean (just an example), I can always do as
Person x = new Spy();
and pass it to another method that might look like
void RegisterForNextBallGame(Person p) { playerList.Add(p.Name); }
This method, unsuspecting that some kind of spy roaming the stadium, falls, performing a simple honest duty!
Edit
To make this clear, this name=********** is still not suitable. He will simply save you from exclusion! Later, you could find a lot of people who walked around the code with the name **********, which would cause subsequent surprises and other problems.
The best solution is the best design. Check Nathan's answer for a hint.
source share