Biju Soman
Biju Soman

Reputation: 438

Call base method from the base class

To remove complexity let me explain it using the below code snippet. I want to call the parent's sum method. Now this code will call recursively and end up in stackoverflow error

public class Program
{
    public static void Main()
    {
        var chd_obj = new child();
        chd_obj.x = 10;
        chd_obj.y=20;
        chd_obj.sum();
    }

    class parent {
        public int x {get;set;}
        public int y {get;set;}

        public  virtual void sum(){
            Console.WriteLine("From Base" + x+y);   
        }
        public virtual void DoSum(){
            this.sum(); // this should call the sum method in the parent class . 
                        //But it is calling the child *sum* method
        }
    }

    class child:parent {

        public override void sum(){
            base.DoSum();
        }

    }
}

Upvotes: 0

Views: 298

Answers (3)

Shervin Ivari
Shervin Ivari

Reputation: 2501

You get in infinite loop cause child class call Dosum method in Base class and again Dosum from base call child class that's why you see StackOverflow exception.

you should define what sum you mean to the compiler so the derived class can not be called again from the base class for many times.

  static void Main(string[] args)
    {
        child sample = new child();
        sample.x = 20;
        sample.y = 15;
        sample.sum();
        Console.ReadLine();
    }

    public class parent
    {
        public int x { get; set; }
        public int y { get; set; }

        public virtual void sum()
        {
            Console.WriteLine("From Base " + (x + y));
        }
        public virtual void DoSum()
        {
            parent a = new parent();
            a.x = this.x;
            a.y = this.y;
            a.sum();
        }

    }

    class child : parent
    {
        public override void sum()
        {
            base.DoSum();
        }
    }

In this way, there is no need to create new methods but you create new instance from your parent class.

Upvotes: 1

relatively_random
relatively_random

Reputation: 5146

You can't do this in C#. There are workarounds, depending on your actual application.

In general, the solution requires you to extract the base's functionality into one or more non-virtual methods.

private void SumCore()
{
    // Do stuff.
}

public virtual void Sum()
{
    SumCore();
}

Upvotes: 1

Sweeper
Sweeper

Reputation: 271135

I don't know if there is a better solution, but I would declare a private method that both sum in the base class and DoSum in the base class call:

private void SumImpl() {
    Console.WriteLine("From Base" + x+y);   
}

public virtual void sum(){
    SumImpl();
}
public virtual void DoSum(){
    SumImpl();
}

Upvotes: 2

Related Questions