Method Overloading
Before going to know all about method overloading, i want to say where it is exactly comes into picture. Lot of programming languages supports default or optional parameters. Example Vb.Net supports optional parameters.
In C#.Net, there is no such type of facility to declare optional parameters as we like.
- Public sub somemethod (a as Integer, b as Integer, optionalc as integer)
-
- End sub
Then this Method overloading concept will be the useful one to overcome this type of problems.
From Framework 4.0 onwards optional parameters are available.
Definition is using the same method name with different type of parameters or different set of parameters is known as Method Overloading.
For example, you want to declare a method with name Addition. But you don't have idea about how many parameters has to declare means addition of two numbers or three numbers or etc, and you don't know about what type of data it is? means Int, float or etc….
See the below code to understand easily,
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication3 {
- class Method_overloading {
- public int Addition(int a, int b) {
- int x;
- return x = a + b;
- }
- public int Addition(int a, int b, int c) {
- int y;
- return y = a + b + c;
- }
- public float Addition(float a, float b) {
- float u;
- return u = a + b;
- }
- public float Addition(float a, float b, float c) {
- float v;
- return v = a + b + c;
- }
- }
-
- class hub {
- public static void Main(String[] args) {
- Method_overloading mthover = new Method_overloading();
- Console.WriteLine("Addition of two integers::::::::::::::::" + mthover.Addition(2, 5));
- Console.WriteLine("Addition of two double type values::::::" + mthover.Addition(0.40 f, 0.50 f));
- Console.WriteLine("Addition of three integers::::::::::::::" + mthover.Addition(2, 5, 5));
- Console.WriteLine("Addition of three double type values::::" + mthover.Addition(0.40 f, 0.50 f, 0.60 f));
- Console.ReadLine();
- }
- }
- }
Happy OOP'ing.............