Compile-time Polymorphism in C#
Compile-time polymorphism, also called static polymorphism, means that the method to be executed is decided during compile time. It is mainly achieved through method overloading in C#.
Features:
- Decided at compile time
- Achieved using method overloading
- Occurs within the same class
- Faster than runtime polymorphism
C# Example:
class Calculator
{
public int Add(int a, int b) { return a + b; }
public double Add(double a, double b) { return a + b; }
public int Add(int a, int b, int c) { return a + b + c; }
}
class Program
{
static void Main()
{
Calculator c = new Calculator();
Console.WriteLine(c.Add(2, 3));
Console.WriteLine(c.Add(2.5, 3.1));
Console.WriteLine(c.Add(1, 2, 3));
}
}
No comments:
Post a Comment