Method Overloading In C#

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.

  1. Public sub somemethod (a as Integer, b as Integer, optionalc as integer)  
  2. //coding goes here  
  3. 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,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. namespace ConsoleApplication3 {  
  5.     class Method_overloading {  
  6.         public int Addition(int a, int b) {  
  7.             int x;  
  8.             return x = a + b;  
  9.         }  
  10.         public int Addition(int a, int b, int c) {  
  11.             int y;  
  12.             return y = a + b + c;  
  13.         }  
  14.         public float Addition(float a, float b) {  
  15.             float u;  
  16.             return u = a + b;  
  17.         }  
  18.         public float Addition(float a, float b, float c) {  
  19.             float v;  
  20.             return v = a + b + c;  
  21.         }  
  22.     }  
  23.     //Now you can use those Addition method four types  
  24.     class hub {  
  25.         public static void Main(String[] args) {  
  26.             Method_overloading mthover = new Method_overloading();  
  27.             Console.WriteLine("Addition of two integers::::::::::::::::" + mthover.Addition(2, 5));  
  28.             Console.WriteLine("Addition of two double type values::::::" + mthover.Addition(0.40 f, 0.50 f));  
  29.             Console.WriteLine("Addition of three integers::::::::::::::" + mthover.Addition(2, 5, 5));  
  30.             Console.WriteLine("Addition of three double type values::::" + mthover.Addition(0.40 f, 0.50 f, 0.60 f));  
  31.             Console.ReadLine();  
  32.         }  
  33.     }  
  34. }  

Happy OOP'ing.............


Similar Articles