A.P.S
A.P.S

Reputation: 1164

Hiding derive class method?

Can we hide the derived class public method so that it is not accessible in Main() function in C#. We can't change the accessors of the derived class method.

public class A
{
    public void Add()
    {
    }    
}       

public class B : A 
{
    public void Multiply()
    {
    }        
}

In main() method in C#

B b = new B();
b.mulitply(); // should give compile time error... Like method not founded.

Is there any way we can do it.

Upvotes: 0

Views: 379

Answers (4)

Jorge Córdoba
Jorge Córdoba

Reputation: 52133

Why don't you just just make the method private?

public class B: A
{
  private void Multiply()
  {
  }
}

If you absolutely can't change B, then the only thing I can think of is creating a full adapter class.

public C
{
  private B instance;

  private void Multiply(){}

  public void Add()
  {
    B.Add();
  }
}

That will force you to "replicate" all the methods in B excepts the one you want.

If you ABSOLUTELY need the class to be "B" you'll have to reverse engine it with reflector and change public field to private or protected.

Upvotes: 0

Sii
Sii

Reputation: 671

The point of function being public is that it can be accessed elsewhere.

You could either inherit privately ? ( doesnt make sense) or declared the member as private or protected so derived class doesnt inherit it.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503519

Absolutely not. It's a public method of a public class. If you shouldn't be able to use it, it shouldn't be public.

(I don't see how the fact that it derives from A is relevant, by the way.)

Upvotes: 5

John Saunders
John Saunders

Reputation: 161831

This request doesn't make any sense. Class B declares a method Multiply. Why would this method ever be hidden? Hidden from whom?

Upvotes: 1

Related Questions