Implicit Type Conversion of Enum?

J

Joe HM

Hello -

I have two Enums for which I would like to define type conversions ...
Public Enum eA
A2 = 0
A2 = 1
End Enum

Public Enum eB
B1 = 2
B2 = 3
B3 = 4
End Enum

Is there a way to define a conversion that maps one Enum to the other
because I would like to do the following ...

Dim AA as eA
Dim BB as eB
....
AA = BB

It does not have to be implicit ... so is there a way to overload
CType()? The following will complie but not work properly since the
Integer representations are different ...
AA = CType(BB, eA)

Is there a way to overload CType for this? I used to do things like
this in C++ where I would overload a conversion operator to get the
implicit conversion.

Any way to do this in VB?

Thanks!
Joe
 
J

Jay B. Harlow [MVP - Outlook]

Joe,
| It does not have to be implicit ... so is there a way to overload
| CType()? The following will complie but not work properly since the
| Integer representations are different ...
| AA = CType(BB, eA)
VB 2005 allows you to overload the CType operator for a type (Class or
Structure) however the method needs to be a Shared within that type. Seeing
as you cannot add methods to Enums, you cannot introduce an overloaded CType
operator between two enums. You could however overload CType between a Class
or Structure and an Enum, by putting the overloaded operator in the Class or
Structure...

I would probably define a helper type that defined the conversions for me,
ala the System.Convert class.

' prevent others from inheriting from MyConvert
Public NotInheritable Class MyConvert

' prevent others from instanciating MyConvert.
Private Sub New
End Sub

Public Shared Function ToA(aB As B) As A
' convert eA to an eB
End Function

Public Shared Function ToB(anA As A) As B
' convert eB to eA
End Function

End Class

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


| Hello -
|
| I have two Enums for which I would like to define type conversions ...
| Public Enum eA
| A2 = 0
| A2 = 1
| End Enum
|
| Public Enum eB
| B1 = 2
| B2 = 3
| B3 = 4
| End Enum
|
| Is there a way to define a conversion that maps one Enum to the other
| because I would like to do the following ...
|
| Dim AA as eA
| Dim BB as eB
| ...
| AA = BB
|
| It does not have to be implicit ... so is there a way to overload
| CType()? The following will complie but not work properly since the
| Integer representations are different ...
| AA = CType(BB, eA)
|
| Is there a way to overload CType for this? I used to do things like
| this in C++ where I would overload a conversion operator to get the
| implicit conversion.
|
| Any way to do this in VB?
|
| Thanks!
| Joe
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top