Martijn
Martijn

Reputation: 24789

Is it possible to hide properties from a derived class?

Class A derive from class B. In class A I want to hide some properties inherited from class B. So when an instance is created of class A, I don't want to expose some properties from class B.

Is this possible?

Upvotes: 3

Views: 1923

Answers (6)

Giuseppe Accaputo
Giuseppe Accaputo

Reputation: 2642

When you derive A from B, you're saying that A is practically the same as B, but it has additional characteristics; it is a specialization of B.

To make an example: a Dog is an Animal. In you're case, you're trying to say that an Animal has fins, but a Dog hasn't; this is definitely not the purpose of inheritance.

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55072

Do you mean like:

class A {
    public virtual int X {
        get { return 1; }
    }
}

class B : A {
    public sealed override int X {
        get { return 2; }
    }
}

class C : B {
    public override int X {
        get { return -1; }
    }
}

If so, yes. (The above provides a compile-time error in C). The meaning here is that A had a property, B implemented it, and wanted to stop anyone sub-classes from doing so.

Upvotes: 0

Dienekes
Dienekes

Reputation: 1548

For achieving that, rather than working on making the property private, avoid inheritance and apply composition (i.e. use interfaces).

Upvotes: 1

Mattias S
Mattias S

Reputation: 4798

You can shadow the members by declaring new ones with the same name (and the new modifier). But that doesn't really hide anything, and doesn't prevent anyone from casting back to B and accessing the members that way.

Are you sure you really want to use inheritance in this case? You may want to read up on http://en.wikipedia.org/wiki/Liskov_substitution_principle

Upvotes: 2

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55489

Is it possible to use private access specifier to your property which you want to hide?

if not, then please go through this link - might help you - c# hide from dervied classes some properties of base class

Upvotes: 2

nos
nos

Reputation: 229058

No, that would defeat the purpose of inheritance. Your class A is a B , thus it has the properties of B

Upvotes: 8

Related Questions