Enums as arguments?

  • Thread starter Thread starter Greg Allen
  • Start date Start date
G

Greg Allen

I have a class that I would like to instantiate with a number of different
enums (rather than copy the code each time for each enum).

Is this possible? If so, how?

I'd like to do something like:

Dim mEnum as System.Enum

Sub New (myEnum as System.Enum)
mEnum = myEnum
End Sub

Ideally, I could pass in my enumeration (by name, I assume) when the
class is instantiated, then within the class I would be able to call
all the methods on the enum (such as ToString, etc.). I haven't been
able to get it working -- maybe it's not possible?

Thanks,

-- Greg Allen
(e-mail address removed)
 
I'm not clear exactly what you are trying to accomplish, but is this close?
Its a simple console program.

Module Module1

Enum MyColors

Red

White

Blue

End Enum

Enum WeatherConditions

Clear

Rainy

Snowing

End Enum

Sub Main()

Console.WriteLine("Do Colors")

Dim myEnumHolder As EnumHolder

Dim colorEnum As MyColors

myEnumHolder = New EnumHolder(colorEnum)

myEnumHolder.ShowAll()

Console.WriteLine("Do Weather")

Dim WeatherEnum As WeatherConditions

myEnumHolder = New EnumHolder(WeatherEnum)

myEnumHolder.ShowAll()

End Sub

Class EnumHolder

Private localEnum As [Enum]

Public Sub New(ByVal theEnum As [Enum])

localEnum = theEnum

End Sub

Public Sub ShowAll()

For Each curVal As String In System.Enum.GetNames(localEnum.GetType())

Console.WriteLine(curVal)

Next

End Sub

End Class

End Module
 
This is pretty close. But I want to be able to convert both to the
underlying integer type
from a string and vice-versa.

Something like this, using your example, in class EnumHolder:

Function EnumString (C as Integer) As String
CType(C,localEnum)
End Function

Function EnumValue (S as String) As LocalEnum
return
CType(System.ComponentModel.TypeDescriptor.GetConverter(GetType(localEnum)).
ConvertFromString(S, localenum)
End Function

This should give you a better idea of what I am trying to do.

Of course, I can't get either return statement to compile successfully. But
there's probably a way to do it.

Thanks,

-- Greg
 
Greg,

Can't you pass in the System.Type of the enum you want to work with
instead (i.e. use GetType(YourEnumType))? That, together with the
methods of System.Enum, should let you do almost anything you want
with enums.



Mattias
 
Back
Top