Polymorphism

Polymorphism encompasses many actions (e.g., inheritance and overloading) used to achieve multiple functions from a single interface.

C# supports polymorphism with virtual methods, inheritance tools, and other tools. Virtual methods allow for working with groups of related or similar objects in a uniform way.

Polymorphism

C# provides two main means of overloading: method or constructor overloading for static polymorphism, and operator overloading for dynamic polymorphism. Review these three types of method overloading.

Different parameters:

void AddItem(int);
void AddItem(int, float);

Different data types:

void Show(int);
void Show(float);

Different parameter order:

void Show(char, int);
void Show(int, char);

Operator overloading consists of applying different operators to different user-defined data types. This example overloads the “+” operator:

Measurement m1;
Measurement m2;
Measurement m3;
m3 = m1+m2;

OVERRIDING

Method overriding allows for invocation of methods of the same signature, of different classes, in the same hierarchy of inheritance, and employing the same class. C# overriding employs the keywords virtual and override.

Derived classes can override methods, however, the method must be declared virtual, abstract, or override. Review the example below:

public class One
{
	public virtual void DoSomething()
	{
		Console.WriteLine(“One::DoSomething”);
	}
}
public class Two : One
{
	public override void DoSomething()
	{
		Console.WriteLine(“Two::DoSomething”);
	}
}

Overrides carry other restrictions:

  1. New, static, and virtual modifiers cannot be used for modification of an override method.
  2. Override does not affect access, and the override method and virtual method must have identical access levels.
  3. The overriding declaration must specify a type identical to the inherited property.

When methods do not override a derived method, they are essentially hiding them. The sealed keyword can also be utilized to hide members and prevent overriding. Simply declare the class as sealed override.