Consider the Employee, Manager, and Assistant classes:
public class Emp
{
public string Name { get; set; }
public Manager Manager { get; set; }
public Assistant Assistant { get; set; }
}
public class Manager : Emp
{
}
public class Assistant : Emp
{
}
The goal is to DISALLOW a piece of code to access a property like this:
var foo = new Manager();
var elmo = new Emp();
elmo.Manager = foo;
elmo.Manager.Manager = new Manager();
//how to disallow access to Manager.Manager ?
Because Manager
inherits from Emp
, it has a .Manager
and .Assistant
property.
Question
Are there any modifiers in .NET's inheritance implementation to remove the .Manager
and .Assistant
properties?
Update
Thank you for your great answers, everyone. I was hoping the simplification and contrivance of Emp/Mgr would show through in this question. It's clear that the inheritance, in this example, should be taken to another commonality (something like Person
, where the classes would share names, birthdates, etc.) Your input is much appreciated!
Doing this would violate the Liskov substitution principle, and is usually a sign of a questionable design. In general, any subclass should be able to be used in any context that a base class would be. If Manager
s don't have .Manager
s, then they aren't Emp
s, and shouldn't inherit from them.
No - because it would break Liskov's Subsitution Principle. Basically, you can add things, but you can't take them away.
You could potentially override the property to throw an exception at execution time, but you can't do it at compile time.
Generally if you want to disallow this sort of thing, you should consider composition rather than inheritance, as you don't have a genuine inheritance relationship.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With