Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET inheritance: suppress a property from the base class

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!

like image 718
p.campbell Avatar asked Jan 19 '10 22:01

p.campbell


2 Answers

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 Managers don't have .Managers, then they aren't Emps, and shouldn't inherit from them.

like image 195
recursive Avatar answered Sep 19 '22 19:09

recursive


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.

like image 27
Jon Skeet Avatar answered Sep 20 '22 19:09

Jon Skeet