Types of Polymorphism
suggest changePolymorphism means that an operation can also be applied to values of other types.
There are multiple types of Polymorphism:
- Ad hoc polymorphism:
function overloading, so a method can be used with different types without being generic.
- Parametric polymorphism:
is the use of generic types. See Generics
- Subtyping:
inheriting a class, or implementing an interface, to share a similar operation.
Ad hoc polymorphism
Ad hoc polymorphism creates a method that can be called with different data types without a conversion at the call, and without generics. Each sumInt overload below has its own implementation:
public static int sumInt( int a, int b)
{
return a + b;
}
public static int sumInt( string a, string b)
{
int _a, _b;
if(!Int32.TryParse(a, out _a))
_a = 0;
if(!Int32.TryParse(b, out _b))
_b = 0;
return _a + _b;
}
public static int sumInt(string a, int b)
{
int _a;
if(!Int32.TryParse(a, out _a))
_a = 0;
return _a + b;
}
public static int sumInt(int a, string b)
{
return sumInt(b,a);
}
Here’s an example call:
public static void Main()
{
Console.WriteLine(sumInt( 1 , 2 )); // 3
Console.WriteLine(sumInt("3","4")); // 7
Console.WriteLine(sumInt("5", 6 )); // 11
Console.WriteLine(sumInt( 7 ,"8")); // 15
}
Subtyping
Subtyping uses a shared base type so each implementation can supply similar behavior:
public interface Car{
void refuel();
}
public class NormalCar : Car
{
public void refuel()
{
Console.WriteLine("Refueling with petrol");
}
}
public class ElectricCar : Car
{
public void refuel()
{
Console.WriteLine("Charging battery");
}
}
Both NormalCar and ElectricCar now have a method to refuel, each with its own implementation. Here’s an example:
public static void Main()
{
List<Car> cars = new List<Car>(){
new NormalCar(),
new ElectricCar()
};
cars.ForEach(x => x.refuel());
}
The output is the following:
Refueling with petrol Charging battery