C# Runtime(Dynamic) Polymorphsim

Runtime(Dynamic) Polymorphsim

Runtime (or dynamic) polymorphism in C# is achieved using method overriding and inheritance. It's one of the foundational principles of Object-Oriented Programming (OOP).

In runtime polymorphism, the overridden method to be invoked is determined at runtime based on the object's runtime type, rather than its compile-time type. This behavior is achieved using a combination of base and derived classes with the virtual, override, and base keywords.

Let's dive into a tutorial on runtime polymorphism in C#:

1. Base Class with Virtual Method:

First, you'll need a base class with a method marked as virtual. This means the method can be overridden by derived classes.

public class Animal { public virtual void Speak() { Console.WriteLine("The animal makes a sound"); } } 

2. Derived Class with Overridden Method:

Now, create a derived class that overrides the virtual method using the override keyword.

public class Dog : Animal { public override void Speak() { Console.WriteLine("The dog barks"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("The cat meows"); } } 

3. Demonstration of Runtime Polymorphism:

Now, let's see runtime polymorphism in action:

public class Program { public static void Main() { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.Speak(); // Outputs: The dog barks myCat.Speak(); // Outputs: The cat meows } } 

Here, even though both myDog and myCat are of type Animal (from a variable declaration standpoint), the runtime types are Dog and Cat, respectively. So, the overridden methods in these derived classes are invoked, showcasing runtime polymorphism.

4. Using the base Keyword:

In some cases, you might want to call the base class's method from the derived class. You can do this using the base keyword:

public class Lion : Animal { public override void Speak() { base.Speak(); // Call the base class method Console.WriteLine("The lion roars"); } } 

Using a Lion object:

Animal myLion = new Lion(); myLion.Speak(); // Outputs: // The animal makes a sound // The lion roars 

Key Points:

  • Virtual Methods: Methods in the base class should be marked with the virtual keyword to allow them to be overridden in derived classes.

  • Override Keyword: In the derived class, you use the override keyword to modify the behavior of the virtual method.

  • Base Keyword: If needed, you can call the base class's version of a method using the base keyword.

Runtime polymorphism is a powerful feature that lets you leverage the principles of OOP to create flexible and reusable code structures. It allows objects of different types to be treated as objects of a common base type and promotes code extensibility and maintainability.


More Tags

application.properties horizontal-scrolling android-vectordrawable jsp eclipse-classpath picasso rustup ssms-2017 paint jce

More Programming Guides

Other Guides

More Programming Examples