Polymorphism in VB.NET

HTML clipboard

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.

Polymorphism Example

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

    Class TestClass
        Public Class Square
            Public x As Double

            ' Constructor:
            Public Sub New(ByVal x As Double)
                Me.x = x
            End Sub

            Public
Overridable Function Area() As Double
                Return
x * x
            End Function
        End
Class

        Private
Class Cube
            Inherits Square
            ' Constructor:
            Public Sub New(ByVal x As Double)
                MyBase.New(x)
            End Sub
            ' Calling the Area base method:
            Public Overrides Function Area() As Double
                Return
(6 * (MyBase.Area()))
            End Function
        End
Class

        Public
Shared Sub MyFormat(ByVal value As IFormattable, ByVal formatString As String)
            Console.WriteLine("{0}" & vbTab & "{1}", formatString, value.ToString(formatString, Nothing))
        End Sub

        Shared
Sub Main()
            Dim x As Double = 5.2
            Dim s As New Square(x)
            Dim c As Square = 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'
            Dim q1 As Cube = DirectCast(c, Cube)' 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
        End Sub
    End
Class

Conclusion

Hope this blog would have helped you in understanding Polymorphism in VB.NET.