Static/compile-time polymorphism

Static polymorphism, also known as function overloading, involves creating functions with the same name but with different numbers or types of parameters. 

The compiler loads the appropriate function based on the input that's passed. Let's go through the following code example to see how it works. Here, we will create two copies of a function called ADD that will differ in terms of the number of parameters accepted by the function:

static int AddNumber (int a, int b)
{
Console.WriteLine("Accepting two inputs");
return a + b;
}
static int AddNumber(int a, int b, int c)
{
Console.WriteLine("Accepting three inputs");
return a + b + c;
}

Now, when the call is made to the function, based on the number of parameters passed, the respective function will be loaded:

int result = AddNumber(1, 2);
Console.WriteLine(result);
int result2 = AddNumber(1, 2, 3);
Console.WriteLine(result2);
Console.ReadLine();

After the program is executed, we will get the following output:

Now, let's consider another example. In the preceding example, we implemented polymorphism based on the number of parameters. In this example, we will implement polymorphism based on the type of parameter:

  1. Create two classes, one each for Dog and Cat
public class Dog 
{
}
public class Cat
{
}
  1. Create two functions with the same name but one accepting the input of a Dog object and another accepting the input of a Cat object:
static void AnimalImplementation(Dog dog)
{
Console.WriteLine("The implementation is for a dog.");
}
static void AnimalImplementation(Cat cat)
{
Console.WriteLine("The implementation is for a cat.");
}

Now, when a call is made to the function, based on the type of parameter, the appropriate function will be loaded:

Cat cat = new Cat();
Dog dog = new Dog();
AnimalImplementation(cat);
AnimalImplementation(dog);
Console.ReadLine();

When the program is executed, it will show the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157