Polymorphism in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

Polymorphism is the ability to define a method or property in a set of derived classes with matching method signatures but provide different implementations and then distinguish the objects' matching interface from one another at runtime when you call the method on the base class.

From within the derived class that has an override method, you still can access the overridden base method that has the same name by using the base keyword. For example, if you have a virtual method MyMethod() and an override method on a derived class, you can access the virtual method from the derived class by using the call base.MyMethod(). Listing 5.53 illustrates this concept.

Listing 5.53: Polymorphism.cs, Polymorphism Example


// notice the comments/warnings in the Main
// calling overridden methods from the base class


using
System;

class
TestClass
{
    public class Square
    {
        public double x;

        // Constructor:
        public Square(double x)
        {
            this.x = x;
        }

        public virtual double Area()
        {
            return x * x;
        }
    }

    class Cube : Square
    {

        // Constructor:
        public Cube(double x)
            : base(x)
        {
        }

        // Calling the Area base method:
        public override double Area()
        {
            return (6 * (base.Area()));
        }
    }

    public static void MyFormat(IFormattable value, string formatString)
    {
        Console.WriteLine("{0}\t{1}", formatString, value.ToString(formatString,
        null));
    }
    public static void Main()
    {
        double x = 5.2;
        Square s = new Square(x);
        Square c = new Cube(x); // This is OK, polymorphic

        // a base reference can refer to the derived object
        Console.Write("Area of Square = ");
        MyFormat(s.Area(), "n");
        Console.Write("Area of Cube = ");
        MyFormat(c.Area(), "n");

        // ERROR: Cube q = new Square(x);
        // Cannot implicitly convert type 'TestClass.Square' to 'TestClass.Cube'
        Cube q1 = (Cube)c; // This is OK, polymorphic
        Console.Write("Area of Cube again = ");
        MyFormat(q1.Area(), "n");
        Console.ReadLine();

        // try uncommenting the following line and see if it works
        // Cube q2 = (Cube) new Square(x);
        // This compiles but is this OK? NO!
        //Runtime Exception occurs here: System.InvalidCastException:
        //An exception of type System.InvalidCastException was thrown.
        // A derived reference should not be transformed from base object,
        // since the orphaned parts may occur in the derived.
        // Cube constructors those may be necessary had not worked up to now for q2.
        // C# compiles code but gives an exception during runtime
    }
}


Figure 5.13 contains the resulting screen output.

fig-5.13.gif

Figure 5.13: Screen Output Generated from Listing 5.53

Conclusion

Hope this article would have helped you in Polymorphism in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all