infotoni91
infotoni91

Reputation: 721

Force base class virtual method call inside of base class

Don't get me wrong: I do not want to force an overriding method to call the base class like already asked 1000...times before :)

I wondered if there is any way to force the call of the base class implementation of a method inside the base class.

Example:

using System;

public class Program
{
    public static void Main()
    {
        var c = new SubClass();
        c.CallInfo();
    }

    internal class BaseClass {
        protected virtual void Info(){
            Console.WriteLine("BaseClass");
        }

        internal virtual void CallInfo() {
            this.Info();
        }
    }

    internal class SubClass : BaseClass {
        protected override void Info() {
            Console.WriteLine("SubClass");
        }

        internal override void CallInfo() {
            base.CallInfo();
        }
    }
}

Output obviously would be SubClass. Is there any way to force the CallInfo method of BaseClass to call its own Info method so that the output would be BaseClass?

Upvotes: 3

Views: 1603

Answers (2)

Nic
Nic

Reputation: 12895

No, you can't do that. The purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called it from base classes.

If that causes problems then the method you want to run should not be a virtual method.

This would work, while it won't force an implementation by a subclass like virtual it'll allow you to override it.

public class Program
{
    public static void Main()
    {
        var c = new SubClass();
        c.CallInfo();
    }

    internal class BaseClass
    {
        protected void Info()
        {
            Console.WriteLine("BaseClass");
        }

        internal virtual void CallInfo()
        {
            this.Info();
        }
    }

    internal class SubClass : BaseClass
    {  
        protected new void Info()
        {
            Console.WriteLine("SubClass");
        }

        internal override void CallInfo()
        {
            base.CallInfo();
        }
    }
}

Upvotes: 1

Keiwan
Keiwan

Reputation: 8301

By marking your Info() method as virtual you are specifically asking for this type of inheritance behaviour to occur.

If you want to ensure that a method call in your base class is not overridden, you'll need to use a non-virtual method, e.g.

internal class BaseClass {
    protected virtual void Info(){
        this.FinalInfo();
    }

    protected void FinalInfo() {
        Console.WriteLine("BaseClass");
    }

    internal virtual void CallInfo() {
        this.FinalInfo();
    }
}

Upvotes: 4

Related Questions