C# Polymorphism

Ok, this is very basic stuff (i mean concept.:D ) but also important. Polymorphism provides a way for a subclass (child class) to define its own version of a method defined by its base class (parent class). This is called “method overriding” and is very common concept in OOP (Object Oriented Programming) such as Java.

Let’s see how this concept works within C#. To re-build your current design, you need to understand the modifiers; virtual and override keywords, and their meanings. Overriding methods in C# is a bit different from doing so in Java, however, the main concept of it remains the same.

If a super class (base class) wishes to define a method that may be (or may be not) overridden by a subclass, it must mark the method with the virtual keyword. These methods with the virtual keyword are called virtual methods.

public class ClassName

{

// This method can be overridden by a derived class.

public virtual void VirtualMethodName(int paraInt)

{

}

}

The same rule is applied to a subclass. When a subclass wishes to change the implementation details of a virtual method, it does so using the override keyword.

class Subclass : SuperClass

{

public override void Method1(int intV)

{

….

base.Method1(10);

}

….

}

Unlike Java, you can leverage the default behavior using the base keyword. In this way (the same as the Java overriding concept, but for those who are new OOP with C#), there is no need to completely re-implement the logic behind Method1(), but can reuse and extend the default behavior of the parent class.

Advertisements