Blue Theme Orange Theme Green Theme Red Theme
 
ANTS Performance Profiler 6.0
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Basic Language » Downcasting in Visual Basic.NET

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. 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.

Author Rank:
Total page views :  2616
Total downloads :  35
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DowncastingVB.zip
 
Become a Sponsor


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.



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.



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.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
This code works without having to directcast to Object by Goofy On November 6, 2009

This works without having to directcast to Object as in the lines highlighted in yellow.
The below code works just as good :

          DirectCast(pers, Lawyer).NumberOfClientsShafted.ToString() & _
          Environment.NewLine)
                    sb.Append("Number of Lies Told: " + _
          DirectCast(pers, Lawyer).NumberOfLiesTold.ToString() & _
          Environment.NewLine)

Reply | Email | Delete | Modify | 
asdf by watches On July 11, 2010
As to many people, owning an authentic louis vuitton purse has become his or her pursuit, and a symbol of status. Why people are willing to buy such an extremely expensive louis vuitton bags ? In the first place, Monogram Roses Canvas has long history famous for its high qualitative sense for leather, especially those leathers having been used for a long time. Monogram Rubis would become honey color.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.