Home All Groups Group Topic Archive Search About

Cast from string to System.DayOfWeek

Author
28 Apr 2006 3:51 PM
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)

Author
28 Apr 2006 4:00 PM
Larry Lard
Charlie Brown wrote:
> 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.

--
Larry Lard
Replies to group please
Author
28 Apr 2006 4:02 PM
Larry Lard
Larry Lard wrote:
Show quoteHide quote
> Charlie Brown wrote:
> > 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)

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.

--
Larry Lard
Replies to group please
Author
28 Apr 2006 4:35 PM
Charlie Brown
Nice.  Thank you.