how can i make this work.

  • Thread starter Thread starter Tariq Ahmad
  • Start date Start date
T

Tariq Ahmad

i have an enum, which is defined like this:

enum MyColour
Blue=0
Green
Red
end enum

i have a function declared like this:

function ProcessColours(col as MyColour)
....
end function

i want to able to call my function like this: ProcessColours("Blue")
instead of ProcessColours(MyColour.Blue)

how can i do this???


if u are wondering why then here it is:
ProcessColours is actually a webmethod, when i go to test this method
i see:

<Colour>BLUE or GREEN or REDCode>

i like this cause it tells the consumer what the methos expects as input.

but when i call the method like this: ProcessColours("BLUE") it complains
that
it cannot convert string to integer .....

thnx for ur help.

t.
 
Polymorphism...

2 functions

processColours(col as MyColor)
and
processColours(ocl as String)

where the string you would basically do a condition to check for it and then
call the other function.
 
Make an overloaded method like this:

'-----------------------------------------------
Enum MyColour
Blue = 0
Green
Red
End Enum

' Main processing function
Function ProcessColours(ByVal col As MyColour)
' Do Stuff
End Function

' Overloaded method to convert string to enum - Ignores case
Function ProcessColours(ByVal col As String)
ProcessColours([Enum].Parse(GetType(MyColour), col, True))
End Function

-------------------------------------------------

Beware though. If the string does not match an enumeration value, a
System.ArgumentException will be thrown.

HTH,

Trev.
 
Hi Tariq,

CodeMonkey gave some pretty handy code and said:
|| Beware though. If the string does not match an enumeration
|| value, a System.ArgumentException will be thrown.

In other words (and allowing for Option Strict On):

' Overloaded method to convert string to enum - Ignores case
Public Overloads Function ProcessColours _
(ByVal sColour As String) As MyColour
Try
Dim oColour As Object
oColour = MyColour.Parse (GetType (MyColour), sColour, True)
ProcessColours (DirectCast (oColour, MyColour))
Catch
MsgBox ("And just what sort of colour do you think " _
& sColour & " is supposed to be???")
End Try
End Function

Public Overloads Function ProcessColours _
(Colour As MyColour) As Object
MsgBox ("Colour is " & Colour.ToString)
End Function

Regards,
Fergus
 
Hello,

Tariq Ahmad said:
enum MyColour
Blue=0
Green
Red
end enum

i have a function declared like this:

function ProcessColours(col as MyColour)
...
end function

i want to able to call my function like this: ProcessColours("Blue")
instead of ProcessColours(MyColour.Blue)

Have a look at the method '[Enum].Parse'.
 
Back
Top