Creating a method in derived class with same signature as a method in base class is called as method overriding.
Same signature means methods must have same name, same number of arguments and same type of arguments.
Method overriding is possible only in derived classes, but not within the same class.
When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.
To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.
Examples for Method Overriding in C#
using System;
namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "New York";
}
}
class DerivedClass : BaseClass
{
public override string YourCity()
{
return "London";
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}
Output
London
Example - 2 implementing abstract method
using System;
namespace methodoverridingexample
{
abstract class BaseClass
{
public abstract string YourCity();
}
class DerivedClass : BaseClass
{
public override string YourCity() //It is mandatory to implement absract method
{
return "London";
}
private int sum(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}
Output
London