Concept of overloading and overriding of C#
Concept of
Overloading and Overriding in c#
Concept of overloading and overriding is very confusing for
beginner. They are very
familiar with two terms but don’t know exact difference between them. If you
are in same category then this article is for you. Here we will try to
understand the concept of overloading and overriding with very simple example.
Before going to discussion we will clear basic concept of
them.
Overloading: - Function name is same but argument set is different
and all functions are within same class.
Overriding:-
Function name is same function argument is same but functions are in different class.
And one class must be derive from other class.
Example of overloading
As per definition, function argument set must be different but
function name will be same and functions are in same class. In below example, we
have implemented simple overloading concept within Myclass class. Here we are
overloading Print() function. If you observe body of Myclass class you will
find three different signature of Print() function where function name is same
but argument type and number are different. And according to passing argument
type and number the appropriate function will invoke.
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using System.Data.Common;
using System.Data;
using System.Reflection;
using System.Globalization;
namespace Test1
{
class MyClass
{
public void Print()
{
Console.WriteLine("sourav Kayal");
}
public void Print(String name)
{
Console.WriteLine(name + " Kayal");
}
public void Print(String name, String surname)
{
Console.WriteLine(name + surname);
}
}
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.Print();
obj.Print("Sourav");
obj.Print("Sourav"," Kayal");
Console.ReadLine();
}
}
}
Example of overriding
In case of overriding the function signature
will be same but they must be define in different class and one class must be
inherited from other class. In below we have implemented sample example to show
overriding concept.
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using System.Data.Common;
using System.Data;
using System.Reflection;
using System.Globalization;
namespace Test1
{
class BaseClass
{
public virtual void Hello()
{
Console.WriteLine("I am base hello");
}
}
class DeriveClass : BaseClass
{
public override void Hello()
{
//base.Hello();
Console.WriteLine("I am derive hello function");
}
}
class Program
{
static void Main(string[] args)
{
DeriveClass objD = new DeriveClass();
objD.Hello(); //Call Hello function of derived class
Console.ReadLine();
}
}
}
In function
definition of base class we have to use virtual keyword and in derive class definition
we have to use override keyword.