• Just like in C++, C# allows you to overload the methods.
• Method overloading is nothing but writing multiple methods with same name.
• To overload methods, you should follow the below rules.
1. All of the overloaded methods name should be same.
2. Any difference between the method arguments should be maintained. The difference may be in no. of arguments or the data types of arguments.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleMethodOverloading
{
class SimpleOverloadDemo
{
public void Show(int n)
{
Console.WriteLine("An integer value is found: " + n);
}
public void Show(double d)
{
Console.WriteLine("A double value is found: " + d);
}
public void Show(string s)
{
Console.WriteLine("A string value is found: " + s);
}
}
class Program
{
static void Main(string[] args)
{
SimpleOverloadDemo sod = new SimpleOverloadDemo();
sod.Show(92);
sod.Show(1043.3948);
sod.Show("Hello, World!");
Console.Read();
}
}
}
Method Overloading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodOverloading
{
class OverloadSample
{
public int GetMax(int a, int b)
{
if (a > b)
return (a);
else
return (b);
}
public double GetMax(double x, double y)
{
if (x > y)
return (x);
else
return (y);
}
public double GetMax(double x, double y, double z)
{
if (x > y && x > z)
return (x);
else if (y > x && y > z)
return (y);
else
return (z);
}
}
class Program
{
static void Main(string[] args)
{
OverloadSample os = new OverloadSample();
Console.WriteLine(os.GetMax(15, 20));
Console.WriteLine(os.GetMax(87.12, 102.8273, 98.56 ));
Console.WriteLine(os.GetMax(87.56, 45.12 ));
Console.Read();
}
}
}
Recursion
• Same as C/C++.
Operator Overloading
• Same as C++, but the “operator” method should be static.