Cast from string to System.DayOfWeek

C

Charlie Brown

I am trying to cast a string to System.DayOfWeek. Don't even know if
this is possible but it would sure save me a lot of headache if it is.

Trying...

Dim strDay As String = "Wednesday"
Dim day As System.DayOfWeek = ctype(strDay, System.DayOfWeek)
 
L

Larry Lard

Charlie said:
I am trying to cast a string to System.DayOfWeek. Don't even know if
this is possible but it would sure save me a lot of headache if it is.

Trying...

Dim strDay As String = "Wednesday"
Dim day As System.DayOfWeek = ctype(strDay, System.DayOfWeek)

DayOfWeek is an Enum, and Enum has the Parse method. The syntax is a
little ugly, but it works:

day = CType(System.Enum.Parse(GetType(DayOfWeek), strDay),
DayOfWeek)

(The reason we have to say System.Enum is because Enum is a VB.NET
keyword. An alternative syntax is

day = CType([Enum].Parse(GetType(DayOfWeek), strDay),
DayOfWeek)

which isn't really much better).

You will get an ArgumentException if the string doesn't match any of
the enum values.
 
L

Larry Lard

Larry said:
DayOfWeek is an Enum, and Enum has the Parse method. The syntax is a
little ugly, but it works:

day = CType(System.Enum.Parse(GetType(DayOfWeek), strDay),
DayOfWeek)

Oops, with a pre-defined enum we can be a little cleaner:

day = CType(DayOfWeek.Parse(GetType(DayOfWeek), strDay),
DayOfWeek)

using the fact that Parse can be invoked directly on a type that
inherits from Enum.
 

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