Shadowing using Shadows in Visual Basic.NET 2005 (Page 1 of 6 )
This article gives you an in-depth understanding of how to use "Shadows" in Visual Basic 2005. You will also see how "overloads" can replace "shadows" in certain situations.
A
downloadable zip file is available for this article.
If you are new to OOP in Visual Basic.NET, I strongly suggest you to go through the following links:
Constructors with Object-Oriented Database Development
Properties and Object-Oriented Database Development
Methods with Object-Oriented Database Development
Introduction to Object-Oriented Database Development
The entire source code for this article is available in the form of a downloadable zip file. The solution was developed using Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Server 2003 Enterprise Edition. I didn't really test it in any other environment. I request that you post in the discussion area if you have any problems in execution.
A simple demonstration of "Shadows" in Visual Basic 2005
In my previous article, I discussed overloading and overriding in Visual Basic 2005. Now, I shall discuss Shadowing in Visual Basic 2005. Before going into the explanation, let us go through the following sample:
Public Class Parent
Public x As Integer = 10
End Class
Public Class Child
Inherits Parent
Public x As Integer = 20
End Class
I defined two classes, "Parent" and "Child," where "Child" gets inherited from "Parent." If I create an object (instance) with respect to "Parent" and access the field (x) as follows, there is no doubt that it displays "10."
Dim obj As New Parent
MessageBox.Show(obj.x)
However, if I create an object with respect to "Child" and access the field (x) as follows, the confusion starts:
Dim obj As New Child
MessageBox.Show(obj.x)
The class "Child" is equipped with the same field (x) twice -- one inherited from "Parent" and one of its own. If such a situation occurs, the field in the "child" shadows the field in "parent." In other words, the child member temporarily hides the parent member and activates its own. This is called shadowing.
Even though we don't specify the word "shadows," the editor gives a warning message and defaults to "Shadows." The rewritten field for the above is as follows:
Public Shadows x As Integer = 20 'default is shadows even if it is not defined
Next: Accessing parent members when using Shadows in Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee