Home > Interview Questions > C#.NET > What is difference between method overloading and overriding in C#?

What is difference between method overloading and overriding in C#?

by Thamil   on 02/10/2015   Category: C#.NET   |  Level: Advance   |  Views: 530    |  Points: 25     |  Gold 


Method overloading

• More then one method or functions in a same class with different parameter/signature is called method overloading
• Also known as early binding which is performed at compile time.
• Overloading can able to perform without inheritance concept
 public class baseclass
{
public string GetUserName(string userID)
{
return userID;
}

public string GetUserName(string userID,DateTime date)
{
return userID;
}
}
class Program
{
static void Main(string[] args)
{
baseclass bc = new baseclass();
string uid = bc.GetUserName("2020");
Console.WriteLine(uid);
uid =bc.GetUserName("2020",System.DateTime.Now); Console.WriteLine(uid);
Console.ReadKey();
}
}

Output
2020
2020
Here you can see, in a class there are two methods with same name and different parameters.
Method overriding

•Creating an method or function in a derived class with same name and same parameter/signature and same return type as in base class is called as method overriding or function overriding
•Also known as late binding which is performing at run time. We can override a method in base class by creating same method in derived class and with help of inheritance, virtual and override keywords.
•Method overriding allows you to change the functionality of a method in child class
public class baseclass
{
public virtual string GetUserName(string userID)
{
string userName = "John";
return userName;
}
}
public class Derivedclass : baseclass
{
public override string GetUserName(string userID)
{
string userFullName = "John Peter";
return userFullName;
}
}

class Program
{
static void Main(string[] args)
{

baseclass bc = new baseclass();
string name = bc.GetUserName("10");
Console.WriteLine(name);
Derivedclass dc = new Derivedclass();
name = dc.GetUserName("10");
Console.WriteLine(name);

}
}


Output
John
John Peter


« Is it possible to create web application without web.config file in Asp.Net?
» What is managed and unmanaged code in .net?
Post Question  |  Question Home

Recent Posts

User Responses


No response found, be the first to review this question.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts