How to: Distinguish Between Two Elements with the Same Name
If your application has access to multiple elements with the same name, you can qualify a name to enable the Visual Basic compiler to match your reference to the particular element you want to use. For more information, see How to: Qualify a Declared Element Name.
Example
The following example shows two variables with the same name in different containing elements with the same name. The variables are declared as Shared purely to make the code shorter in the example.
Namespace space1
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 1"
End Class
End Namespace
Namespace space2
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 2"
End Class
End Namespace
Public Module callShowMe
Public Sub showStrings()
MsgBox("From space1: " & space1.innerClass.showMe _
& vbCrLf & "From space2: " & space2.innerClass.showMe)
End Sub
End Module
The preceding example declares two variables, each named showMe
, and each inside a class named innerClass
. Because both containing elements have the same name, the calling code must not only qualify the variable showMe
with its container innerClass
, but it must also qualify innerClass
with its container space1
or space2
. The Visual Basic compiler can resolve each reference because each qualification string provides an unambiguous path to a unique declaration.
Robust Programming
The fewer variables with the same name you have declared, the fewer opportunities you have for accidentally referring to one in place of another. You can also minimize problems of reference matching.
Security
The fewer variables with the same name you have declared, the smaller the chances that malicious code can make improper use of one of them.
See Also
Tasks
How to: Qualify a Declared Element Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Concepts
Declared Element Characteristics
Resolving a Reference When Multiple Variables Have the Same Name
Declaration Statements in Visual Basic