Udostępnij za pośrednictwem


Enumerations and Name Qualification (Visual Basic)

Normally, when referring to a member of an enumeration, you must qualify the member name with the enumeration name. For example, to refer to the Sunday member of your Days enumeration, you would use the following syntax:

X = Days.Sunday

Using the Imports Statement

You can avoid using fully qualified names by adding an Imports statement to the namespace declarations section of your code, as in the following example:

Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays

An Imports statement imports namespace names from referenced projects and assemblies and from within the same project as the module in which the statement appears. Once this statement is added, you can refer to your enumeration members without qualification, as in the following example:

X = Sunday

By organizing sets of related constants in enumerations, you can use the same constant names in different contexts. For example, you can use the same names for the weekday constants in the Days and WorkDays enumerations. If you use the Imports statement with your enumerations, you must be careful to avoid ambiguous references. Consider the following example:

Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays
Public Sub New()
  ' Insert code to implement constructor.
  X = Monday
End Sub

Assuming that Monday is a member of both the Days enumeration and the Workdays enumeration, this code generates a compiler error. To avoid ambiguous references when referring to an individual constant, qualify the constant name with its enumeration. The following code refers to the Saturday constants in the Days and WorkDays enumerations.

X = Days.Saturday
Y = WorkDays.Saturday

See Also

Tasks

How to: Declare Enumerations (Visual Basic)

How to: Refer to an Enumeration Member (Visual Basic)

How to: Iterate Through An Enumeration in Visual Basic

How to: Determine the String Associated with an Enumeration Value (Visual Basic)

Reference

Enum Statement (Visual Basic)

Imports Statement (.NET Namespace and Type)

Data Type Summary (Visual Basic)

Concepts

Constants and Enumerations (Visual Basic)

When to Use an Enumeration (Visual Basic)

Constant and Literal Data Types (Visual Basic)