I am trying to achieve calling methods of the Base class and the Derived class. However, I am a little confused if I am doing it correctly. I would like to set values from the Base class and use them in the Derived class.
namespace Inheritance
{
using System;
public class BaseClass
{
public BaseClass() { }
protected string methodName;
protected int noOfTimes;
public void Execute(string MethodName, int NoOfTimes)
{
this.methodName = MethodName;
this.noOfTimes = NoOfTimes;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass() : base() { }
public void Execute()
{
Console.WriteLine("Running {0}, {1} times", base.methodName, base.noOfTimes);
}
}
public class Program
{
static void Main(string[] args)
{
DerivedClass d = new DerivedClass();
d.Execute("Func", 2);
d.Execute();
Console.ReadLine();
}
}
}
Question: can I achieve the same as above using only 1 call to Execute instead of 2?
I hope my example above is clear. Please let me know if its otherwise and I will provide additional details.
Thanks
Disclaimer, my answer assumes you wanted a solution revolving around inheritance of the method and it’s implementation. Other answers provided are also good solutions to the question.
It sounds like you want to override a method in a derived class. To do this, the base class needs to mark the method
virtualorabstract. However, in your case the derived class method signature is different. I will assume that this is an error in not understanding how it would work, so I have corrected it for you.In this instance, the derived class marks the method with
override, a C# keyword. I then callbase.Execute(MethodName, NoOfTimes);as I want to use the base class’s implementation in my overridden implementation. I then put in my own code.baseis another keyword that lets you access members in the base class immediately below the class you are in without having the inheritance chain push you back into derived members.abstractis worth reading up on, but is not required in this case (it has different behaviour tovirtualbut also gets used in conjunction withoverride).There are a few code formatting and naming quirks with this sample, but I will leave this alone to stay as close to your original code as possible.