C# Tutorial
The word polymorphism means having many forms.
C# polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Polymorphism uses inheritance methods to perform different tasks. This allows us to perform a single action in different ways..
Polymorphism is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
using System;
namespace HelloWorld
{
class Students // base class (parent)
{
public void stumsg() {
Console.WriteLine("Code Always") ;
}
}
class SectionA : Students { // Derived class (child)
public void stumsg() {
Console.WriteLine("Code C++") ;
}
}
class SectionB : Students { // Derived class (child)
public void stumsg() {
Console.WriteLine("Code C#") ;
}
}
class Program
{
static void Main(string[] args)
{
Students stu = new Students(); // Create a Students object
Students secA = new SectionA(); // Create a SectionA object
Students secB = new SectionB(); // Create a SectionB object
stu.stumsg();
secA.stumsg();
secB.stumsg();
}
}
}
When the above code is compiled and executed, it produces the following result −
The output from the example above was probably not what you expected. That is because the base class method overrides the derived class method, when they share the same name.
C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods:
using System;
namespace HelloWorld
{
class Students // base class (parent)
{
public virtual void stumsg() {
Console.WriteLine("Code Always") ;
}
}
class SectionA : Students { // Derived class (child)
public override void stumsg() {
Console.WriteLine("Code C++") ;
}
}
class SectionB : Students { // Derived class (child)
public override void stumsg() {
Console.WriteLine("Code C#") ;
}
}
class Program
{
static void Main(string[] args)
{
Students stu = new Students(); // Create a Students object
Students secA = new SectionA(); // Create a SectionA object
Students secB = new SectionB(); // Create a SectionB object
stu.stumsg();
secA.stumsg();
secB.stumsg();
}
}
}
When the above code is compiled and executed, it produces the following result −