yo chauhan
yo chauhan

Reputation: 12315

Decreasing the visibility of base class properties

I had created a base class that has many public properties and were been used perfectly. Now i want to use this class to derive other class , but i do'nt want some of its properties to be exposed outside the derived class that inherits it. Is there any way that the properties of base class that are public cannot be exposed outside its derived class.(The properties that are to be hidden are public because they are used in other classes that inherits it).Any help will be highly appericiated.

Upvotes: 0

Views: 948

Answers (3)

JaredPar
JaredPar

Reputation: 755457

What you're asking for is simply not possible. If type B inherits from type A then it "is-a" type A. B has at least the same accessible contract that type A had. There is no way to hide a public member of A without fundamentally violating this contract.

If you find yourself in a scenario where you want to use A but only expose a subset of the properties then inheritance is not the right solution: containment is the proper solution.

public class B { 
  private A m_wrapped;

  // Expose only the properties you want to expose here
}

Upvotes: 1

payo
payo

Reputation: 4561

I agree with cadrell0 about marking them protected, but just in case you are looking for a solution where the properties are actually public, but hidden to users of a certain derived class, you can use an explicit interface

interface IHaveMethodsYouCanHide { void Foo(); }
class Base : IHaveMethodsYouCanHide { public void Foo() {} }
class NonHidingDerived : Base { }
class HidingDerived : Base, IHaveMethodsYouCanHide
{
  void IHaveMethodsYouCanHide.Foo() {}
}

With this code, identifers of type HidingDerived will not allow calls to Foo (unless first cast to IHaveMethodsYouCanHide).

Upvotes: 1

cadrell0
cadrell0

Reputation: 17327

You want to make them protected.

From MSDN:
A protected member is accessible within its class and by derived class instances.

Upvotes: 5

Related Questions