Overriding Methods

G

Guest

Can you override a method of a class within a class?

Example:
======================================>
public abstract class A

{

public abstract void Method1();

public abstract class B

{

public abstract void Method2();

}

}


public class C : A

{

public override ...

}

======================================||

In class C, derived from class A, I want to override Method2 of class B.

Thanks.
 
J

Jon Skeet [C# MVP]

Gaijin said:
Can you override a method of a class within a class?

In class C, derived from class A, I want to override Method2 of class B.

No - you can only override methods within a class derived from the one
containing the method you want to override.
 
G

Guest

no because class B is not in your inheritance hierarchy

----- Gaijin wrote: ----

In class C, derived from class A, I want to override Method2 of class B.

Thanks.
 
B

Bjorn Abelli

Gaijin wrote:



No - you can only override methods within a class derived
from the one containing the method you want to override.

However, you can override it in another class, within the derived class C,
such as:

public class C : A
{
public override void Method1() { ... }

public class D : B
{
public override void Method2() { ... }
}
}

This makes it possible to do something in the way I believe the OP was
thinking of:

A.B ab = new C.D();
ab.Method2();

However, whether it's useful or not is another question...

// Bjorn A
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top