Overloading:
Overloading allows you to have a class that has multiple methods with the same name, but with a different number and order of arguments that accomplish a similar task. You should use overloading and only when doing so makes it easier for other developers to better understand your overloaded methods behavior should be consistent across all methods
Example of overloading:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
A MyA = new A();
MyA.Display();
MyA.Display(10);
}
}
public class A
{
public void Display()
{
Console.WriteLine("no params display method");
}
public void Display(int A)
{
Console.WriteLine("overloaded display{0}", A);
Console.ReadKey();
}
}
}
Overriding:
Three keywords are related to overriding methods
1)override
2)base
3)new
All these allow you to use polymorphism, access an overridden method, and indicate a method override
Override
The override keyword is used to invoke polymorphism. It allows a derived class to provide a method with the same name and parameters. The derived class may enhance or modify a method that is inherited through a base class
Base
The base keyword is used to access the base method that has been overridden. Remember that C# supports only single inheritance. If you have class C derived from class B, Which is derived from class A, and each class has a virtual or overridable version of the same method, You can call only the method that is in the base class, not in the base class of the base class
New
The new keyword, In addition to being used to allocate memory, Can also be used to hide data members, methods, and type members of a base class. The new keyword is implied and is used to signal that a method has been replaced in the derived class. This keyword is not required, but it is recommended for code readability. Any derived class that implements a method with the same signature will be treated as if it had been marked as new
Example of overriding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
A MyA = new D();
B MyB = new C();
MyA.Display();
MyB.Display();
}
}
class A
{
public virtual void Display()
{
Console.WriteLine("class A display method");
}
}
class B : A
{
public override void Display()
{
Console.WriteLine("class b's display method");
}
}
class C:B
{
public override void Display()
{
Console.WriteLine("class c's display method");
}
}
class D : C
{
public override void Display()
{
Console.WriteLine("class D's display method");
Console.ReadKey();
}
}
}