Curriculum
Polymorphism is the ability of an object to take on many forms or have many different behaviors depending on the context in which it is used. In C#, polymorphism can be achieved through method overloading, method overriding, and interfaces.
Here’s an example of polymorphism in C# using method overriding:
public class Animal { public virtual void MakeSound() { Console.WriteLine("Animal is making a sound"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof!"); } }
In this example, we have a base class Animal
with a virtual method MakeSound()
. We also have two derived classes Cat
and Dog
that override the MakeSound()
method with their own implementation.
Now, we can create instances of Cat
and Dog
and call the MakeSound()
method on them:
Animal myCat = new Cat(); myCat.MakeSound(); // Output: Meow! Animal myDog = new Dog(); myDog.MakeSound(); // Output: Woof!
Even though we are using the Animal
type to create these objects, the MakeSound()
method will behave differently depending on whether the object is a Cat
or a Dog
. This is an example of polymorphism in action.
We can also achieve polymorphism using method overloading. Here’s an example:
public class Calculator { public int Add(int num1, int num2) { return num1 + num2; } public int Add(int num1, int num2, int num3) { return num1 + num2 + num3; } }
In this example, we have a Calculator
class with two Add()
methods that have different parameter lists. When we call the Add()
method on an instance of Calculator
, C# will automatically choose the correct version of the method based on the number and types of arguments that we provide:
Calculator calculator = new Calculator(); int sum1 = calculator.Add(2, 3); // Output: 5 int sum2 = calculator.Add(2, 3, 4); // Output: 9
Here, the first Add()
method takes two integers as arguments, and the second Add()
method takes three integers as arguments. Depending on how many arguments we provide when we call the Add()
method, C# will choose the appropriate method to execute. This is another example of polymorphism in C#.
In summary, polymorphism is the ability of an object to take on many forms or have many different behaviors depending on the context in which it is used. In C#, polymorphism can be achieved through method overloading, method overriding, and interfaces. By using polymorphism in our code, we can create more flexible and reusable software that can handle a variety of situations.