Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# doesn't support base.base?

I tested code like this:

class A
{
    public A() { }

    public virtual void Test ()
    {
        Console.WriteLine("I am A!");
    }
}

class B : A
{
    public B() { }

    public override void Test()
    {
        Console.WriteLine("I am B!");
        base.Test();
    }
}

class C : B
{
    public C() { }

    public override void Test()
    {
        Console.WriteLine("I am C!");
        base.base.test(); //I want to display here "I am A"
    }
}

And tried to call from C method Test of A class (grandparent's method). But It doesn't work. Please, tell me a way to call a grandparent virtual method.

like image 333
Vasya Avatar asked Oct 04 '11 13:10

Vasya


People also ask

Why C is the best language?

It is fast The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Why should you learn C?

It helps you understand how a computer works By learning C, you can be able to understand and visualize the inner workings of computer systems. This can include aspects like allocation and memory management along with their architecture and the overall concepts that drive programming.

Why do people use C?

The biggest advantage of using C is that it forms the basis for all other programming languages. The mid-level language provides the building blocks of Python, Java, and C++. It's a fundamental programming language that will make it easier for you to learn all other programming languages.

Why semicolon is used in C?

Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.


1 Answers

You can't - because it would violate encapsulation. If class B wants to enforce some sort of invariant (or whatever) on Test it would be pretty grim if class C could just bypass it.

If you find yourself wanting this, you should question your design - perhaps at least one of your inheritance relationships is inappropriate? (I personally try to favour composition over inheritance to start with, but that's a separate discussion.)

like image 133
Jon Skeet Avatar answered Oct 16 '22 05:10

Jon Skeet