Re: How to "increment" an Enum? by Jay
Jay
Sat Jun 12 10:59:09 CDT 2004
Bob,
Just be aware that you may wind up with an invalid Enum value, without an
exception!
Consider the following:
Dim currentState As State = State.Third
> > nextState = Ctype(CType(currentState, integer) + 1, State)
nextState will actually have the value of 3, however First = 0, Second = 1,
Third = 2. What value does 3 represent?
You can use System.Enum.IsDefined to ensure that nextState is valid.
Hope this helps
Jay
"Bob Altman" <rda@nospam.com> wrote in message
news:%23kKS2JJUEHA.808@tk2msftngp13.phx.gbl...
> Thanks Tom. I was looking for some magic method on either the Convert
class
> or the Enum class. It never occurred to me to do the obvious thing and
> simply cast my enum to int and back again. Thanks again!
>
> - Bob
>
> "Tom Dacon" <Tom-@t-dacons.com> wrote in message
> news:%23CmnYbBUEHA.712@TK2MSFTNGP11.phx.gbl...
> > Sorry about the C# example; I went back and read your original post and
> saw
> > that it was in VB.Net. Under Option Strict in VB.Net, the following line
> of
> > code works:
> >
> > nextState = Ctype(CType(currentState, integer) + 1, State)
> >
> > HTH,
> > Tom Dacon
> > Dacon Software Consulting
> >
> > "Tom Dacon" <Tom-@t-dacons.com> wrote in message
> > news:e$0YnXBUEHA.3336@TK2MSFTNGP10.phx.gbl...
> > > Here's what I started with:
> > >
> > > State startWith = State.First;
> > > State next = (State)((int)(startWith) + 1);
> > >
> > > but then just on a whim I tried this:
> > >
> > > State startWith = State.First;
> > > State next = startWith + 1;
> > >
> > > and it worked just as well (at least on VS2003).
> > >
> > > However you do it, you'll probably want to supply a little code to
make
> > sure
> > > that it doesn't get incremented 'off the end' of the enumeration.
> > >
> > > HTH,
> > > Tom Dacon
> > >
> > > "Bob Altman" <rda@nospam.com> wrote in message
> > > news:uVqjVMBUEHA.972@TK2MSFTNGP10.phx.gbl...
> > > > Hi all,
> > > >
> > > > I have an Enum declared (in VB) as:
> > > >
> > > > Private Enum State
> > > > First
> > > > Second
> > > > Third
> > > > End Enum
> > > >
> > > > If I have an instance of this enum, how can I "increment" it? For
> > > example:
> > > >
> > > > Dim currentState as State = State.First ' currentState is 0
> > > > currentState = <some expression yielding State.Second, i.e. 1>
> > > >
> > > > TIA,
> > > >
> > > > - Bob
> > > >
> > > >
> > >
> > >
> >
> >
>
>