calling base of base

  • Thread starter Thread starter Sebastiaan Olijerhoek
  • Start date Start date
S

Sebastiaan Olijerhoek

How can I call the Root.Method() from B.Method()

class Root
{
public Root()
{
}

private virtual void Method()
{
}
}

class A : Root
{
public A()
{
}

private virtual void Method()
{
base.Method();
}
}

class B : A
{
public B()
{
}

private virtual void Method()
{
// How to call base of base?
base.base.Method(); //Error CS1041
(this as Root).Method() ; /Error CS1540
Root.Method(); //Error CS1540
}

Any idea?

Sebastiaan.
}
 
Sebastiaan Olijerhoek said:
How can I call the Root.Method() from B.Method()

You can't. For one thing you've actually defined three entirely
separate methods in the code, because they're private. (There's no
point in making a virtual method private.)

Assuming you *actually* meant to make them non-private methods, with
A.Method overriding Root.Method, and B.Method overriding A.Method, you
still can't - you can only call "one level higher".
 
Sebastiaan,

I am not sure why you would need to call up the hierarchy like this, whilst
missing part of the hierarchy out. It is much more common to see something
like the following, which passes a call up the hierarchy:

class Root
{
public Root()
{
}

protected virtual void Method()
{
}
}

class A : Root
{
public A()
{
}

protected virtual void Method()
{
base.Method();
}
}

class B : A
{
public B()
{
}

protected virtual void Method()
{
base.Method();
}
}

Are you sure the above cannot be adapted to suit your purposes? Perhaps with
a parameter to control which levels code executes?

If you absolutely must call just the root method, you could add a special
method into A, such as:
protected void CallBaseMethod()
{
base.Method();
}
and call that from Method() in class B. Not pretty though!

Cheers,
Chris.
 
Chris,
You are right it should be protected override methods.

Your solution doesn't work for me as class A is a class in a 3rd party
library and class Root is of the .NET framework.

Kind regards,
Sebastiaan.
 
What is Root?, what is the 3rd party library?

Sebastiaan Olijerhoek said:
Chris,
You are right it should be protected override methods.

Your solution doesn't work for me as class A is a class in a 3rd party
library and class Root is of the .NET framework.

Kind regards,
Sebastiaan.
 
Back
Top