[ACCEPTED]-how to hide parent property from child class-inheritance

Accepted answer
Score: 11

So it sounds like you are asking the following. You 13 have

class Parent {
    public SomeType ParentProperty { get; set; }

class Child : Parent { }

and you want to hide SomeProperty from being visible 12 in instances of Child.

Do not do this! Do not 11 hide properties from the base class that 10 are visible. First, it's easy to get around:

Parent p = new Child();
p.ParentProperty; // oops!

Second, it's 9 a huge violation of the Liskov substitution principle. Basically, the 8 principle says that anything that you know 7 to be true about all instances of Parent should 6 also be true about all instances of Child. Here, we 5 know that all instances of Parent have a visible 4 property called ParentProperty of type SomeType. Therefore, the 3 same should (moral should) be true of all 2 instances of Child.

Can you tell us why you want 1 to do this and maybe we can suggest an alternative?

Score: 3


You have a design issue if you need 7 this. The Liskov Substitution Principle tells you that your Child class should 6 be substitutable for a Parent class. That means 5 that all code which uses a Parent class should 4 be able to use your Child class instead. This 3 is not the case if you would remove a property. You 2 couldn't replace a Parent with a Child wherever 1 that particular property is used.

Score: 2

I guess the obvious question/answer is, maybe 3 you should just make the property private. (unless 2 of course you have no access to the source 1 to begin with)

Score: 1

Hope this help, you can shadow the property 1 and set it readonly :)

Score: 0

If you derived class when you say child 17 class there's luckily no way to make it 16 go a way. To why that would be bad tale 15 a look at this code:

base myObj = objectFactory.Create(); myObj.theMethodHiddenAway();

the 14 factory Can return any object of type base 13 including all classes that derive from base. The 12 compiler needs to decide what version of 11 theMethodHiddenAway to call compile time 10 (overload resulution) and since it does 9 not no the concrete type compile time, if 8 it was possible to make a method go away 7 by inheritance the compiler wouldn't know 6 if theMethodHiddenAway even existed.

I'd 5 suggest you look at your design since what 4 you're asking smells like one of two design 3 flaws. Either the method does not belong 2 there in the first place or you derived 1 class shouldnt inherit from the base class

Score: 0

You can't. A child class reference will 4 always be implicitly convertable to a parent 3 class reference, so you can't prevent the 2 property from being used wihtout removing 1 it from the parent class.

More Related questions