Monday, June 25, 2012

How to Downcast in VB.NET

Visual Basic (VB) is a computer programming language and integrated development environment (IDE) developed by Microsoft based on the Basic computer language. The .NET version allows programmers to create programs for the .NET Framework. Downcasting, as it refers to programming, is the process of refining a reference from a derived class to its base class. Downcasting is mostly seen in C++, C# and Java programming languages, but it can also be done in VB.NET. In VB.NET, casting is usually automatic once an object has been assigned to a variable. However, you can turn off the automatic casting function and specify the downcasting in the VB.NET code. 

Instructions:

1. Open VB.NET or Visual Basic 2010. The .NET version of the IDE is the first to use the .NET Framework. The 2010 version also allows for programming with the .NET Framework. Choose to open an existing project or start a new one from the Welcome screen.

2. Click on the "View" menu item and then "Code" to open the Code Editor. You can also right-click anywhere on a form and then "View Code" to also open the Code Editor.

3. Change the "Option Strict" property to "On" at the top of the VB.NET code by adding the following line:

"Option Strict On"

This turns off the automatic casting function in VB.NET and ensures that the only casting that will be done will be specified by the programmer.

4. Use the "DirectCast" operator to do explicit casting. Also, use the "GetType" operator to ensure that the object that you are working with is valid for downcasting. For instance, if you want to do downcasting on a text box, the code will be:

"Dim x As System.Type

x = txtExample.GetType()

MessageBox.Show(x.FullName)

If TypeOf x Is TextBox Then

x = DirectCast(txtExample, TextBox)

End If"

5. Click on the "Save" icon to save the changes to the code.

 


 

No comments:

Post a Comment