Tuesday, October 30, 2007 6:55 AM kevinisom

Setting the enum from it's name

I've changed this a bit due to some comments

   1:  enum Directions
   2:  {
   3:      Up,
   4:      Down,
   5:      Left,
   6:      Right
   7:  }
   8:  void DoSomething()
   9:  {
  10:      
  11:      Directions currentState =(Directions) Enum.Parse(typeof(Directions), "Down"); 
  12:  }

Comments

# re: Getting the name of an enum

Monday, October 29, 2007 12:54 AM by Bill

Just as a tip, you should probably start the enum at 0 instead of 1 (with Off as 0 because it better translates to False).

This way other states can also be represented (like Starting, Paused, ShuttingDown or Waiting).

# re: Getting the name of an enum

Monday, October 29, 2007 1:50 AM by jayson knight

You can just call ToString() on myStateList and it will return the same thing. If the values are bitwise or'd in the instance, you'll get a comma separated list. A little simpler ;-).

# re: Getting the name of an enum

Monday, October 29, 2007 9:46 AM by Joe Chung

Kevin, for On and Off, why not just use a Boolean instead?

Bill, 0 != false in C#.

# re: Setting the enum from it's name

Tuesday, October 30, 2007 7:54 AM by jayson knight

You still should always have a 'None' value that equates to zero.

blogs.msdn.com/.../134208.aspx

Leave a Comment

(required) 
(required) 
(optional)
(required)