Downcasting in Visual Basic.NET

This article describes a simple approach to downcasting in Visual Basic; downcasting merely refers to the process of casting an object of a base class type to a derived class type.

Introduction

This article describes a simple approach to downcasting in Visual Basic; downcasting merely refers to the process of casting an object of a base class type to a derived class type. Upcasting is legal in Visual Basic as the process there is to convert an object of a derived class type into an object of its base class type. In spite of the general illegality of downcasting you may find that when working with generics it is sometimes handy to do it anyway.

downcasting-window-in-windows8.gif

Figure 1: Test Application in Use

The Solution

The example solution provided is in the form of a Windows form application. The application contains a single form along with three separate classes. The Person class serves as the base class in this example and Lawyer is derived from the Person class. The "PeopleHandler" class offers a single method used to save objects of either the Person or the Lawyer class.

demonstration project-in-windows8.gif

Figure 2: The demonstration project

The Code: Person Class

The project contains two classes used to provide an example of a base class and a derived class. They are the person class (the base) and the lawyer class (derived from person). The person class contains some basic information about a person whilst the lawyer class inherits from the person class and contains a couple of additional properties: The two classes serve no purpose other than to give us an example base and derived class.

Public Class Person

    Private mFirstName As String
    Private mMiddleName As String
    Private mLastName As String
    Private mAge As Integer

    Public Property FirstName() As String
        Get
            Return mFirstName
        End Get
        Set(ByVal value As String)
            mFirstName = value
        End Set
    End Property

    Public Property MiddleName() As String
        Get
            Return mMiddleName
        End Get
        Set(ByVal value As String)
            mMiddleName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return mLastName
        End Get
        Set(ByVal value As String)
            mLastName = value
        End Set
    End Property

    Public Property Age() As Integer
        Get
            Return mAge
        End Get
        Set(ByVal value As Integer)
            mAge = value
        End Set
    End Property

End Class

The Code: Lawyer Class

The lawyer class inherits from Person and adds a couple of additional properties appropriate for lawyers:

Public Class Lawyer
    Inherits Person

    Private mNumberOfClientsShafted As Integer
    Private mNumberOfLiesTold As Integer

    ''' <summary>
    ''' This should probably be a long
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property NumberOfClientsShafted() As Integer
        Get
            Return mNumberOfClientsShafted
        End Get
        Set(ByVal value As Integer)
            mNumberOfClientsShafted = value
        End Set
    End Property

    ''' <summary>
    ''' This ought to be a long too
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property NumberOfLiesTold() As Integer
        Get
            Return mNumberOfLiesTold

        End Get
        Set(ByVal value As Integer)
            mNumberOfLiesTold = value
        End Set
    End Property

 End Class

The Code: Lawyer Class

What now makes this all interesting is if we wanted to use a single method to save either a person or a lawyer (I'm going out on a limb here in indicating that lawyers inherit from persons). To illustrate the point, I built a separate class entitled, "PeopleHandler". The sole method contained in this class can accept either a person or one of person's derived class which is in this case only lawyers. Now, if we pass the following method an object of the person type, everything is fine and all properties are visible in the code. However, if we pass in object of the lawyer type (the derived class), the object is treated as a person rather than a lawyer and the other lawyer properties are invisible to the code even though the lawyer object passed to the "SavePerson" method contains both properties. Since downcasting is not permitted, it is necessary to cast the lawyer as a lawyer rather than as a person; unfortunately, that does not work.

If you tried this: "DirectCast(pers, Lawyer)", the code would show an error indicating that one cannot cast T as a lawyer. Well, in this case, we know full well that "pers" is really a lawyer and not a person so it would be really helpful if we could use it as a lawyer rather than as a person.

In the following bit of code (highlighted) you can see a solution to the dilemma and it is pretty easy, just convert the lawyer to an object and then cast is over to lawyer; that works. After doing that, you will find that you can access the additional properties of the lawyer without difficulty. To avoid any problems with that, I get the type of object passed into the method and use a switch statement to limit my attempts to read lawyer properties to lawyer objects only. You may prefer to use TryCast to DirectCast and provide additional code to handle a TryCast failure.
The code that I used is provided in the following:

Imports System.Collections.Generic
Imports System.Text

Public
Class PeopleHandler

    Public Shared Function SavePerson(Of T)(ByVal pers As Person) As String

        Try
            Dim sb As New StringBuilder()

            Dim tPers As Type = pers.GetType()
            Dim arr As String() = tPers.ToString().Split(".")
            Dim personType As String = arr(arr.Length - 1)

            Dim mAge As Integer = pers.Age
            Dim mFirstName As String = pers.FirstName
            Dim mMiddleName As String = pers.MiddleName
            Dim mLastName As String = pers.LastName

            Select Case personType

                Case "Person"
                    sb.Append("Save Type: " + personType &
                    Environment.NewLine)
                    sb.Append("Name: " + mFirstName + " " + mMiddleName + " "
                              + mLastName & Environment.NewLine)
                    sb.Append("Age: " + mAge.ToString() &
                              Environment.NewLine)
                Case "Lawyer"
                    sb.Append("Save Type: " + personType &
                              Environment.NewLine)
                    sb.Append("Name: " + mFirstName + " " + mMiddleName + " "          
                              + mLastName & Environment.NewLine)
                    sb.Append("Age: " + mAge.ToString() &
                              Environment.NewLine)
                    sb.Append("Number of Clients Shafted: " + _
                              DirectCast(DirectCast(pers, Object),
                              Lawyer).NumberOfClientsShafted.ToString() & _
                              Environment.NewLine)
                    sb.Append("Number of Lies Told: " + _
                              DirectCast(DirectCast(pers, Object),
                              Lawyer).NumberOfLiesTold.ToString() & _
                              Environment.NewLine)
                Case Else
                    sb.Append("Nothing there")
           End Select

             Return sb.ToString()

        Catch ex As Exception

            Return ex.Message

         End Try

    End Function

End Class

The Form1 Class

The form1 class itself is used to test the People Handler's "SavePerson" method by passing it an object of type person and an object of type lawyer. The results of running the executable will display information about both the person and lawyer objects passed to the method.

public class Program
    {
        static void Main(string[] args)
        {
            Person MacDuff = new Person();
            MacDuff.Age = 44;
            MacDuff.FirstName = "Alexander";
            MacDuff.MiddleName = "Hercules";
            MacDuff.LastName = "MacDuff";

            PeopleHandler.SavePerson(MacDuff);

            Console.WriteLine(Environment.NewLine);

            Lawyer creep = new Lawyer();
            creep.FirstName = "Gordon";
            creep.MiddleName = "Bud";
            creep.LastName = "Miller";
            creep.Age = 50;
            creep.NumberOfLiesTold = 100000;
            creep.NumberOfPeopleShafted = 5000;

            PeopleHandler.SavePerson(creep);

            Console.Read();
        }
    }

Summary

This example provided an approach to downcasting; the article provides an example showing how downcasting might be useful when saving base and derived class objects using a common save method.