Groups | Blog | Home
all groups > dotnet framework > march 2008 >

dotnet framework : Switching on Enum Problem


coconet
3/18/2008 4:19:41 PM
Using .NET 3.5.

This does not work, how can I make it switch correctly?

Thanks.





[Flags]
public enum ColorModes
{
red = 2 ,
green = 4 ,
blue = 8
}


public class MyClass
{
public ColorModes CurrentMode{ get; set; }
public void Do()
{
ColorModes currentMode =
(ColorModes)Enum.Parse( typeof( ColorModes ) ,
this.CurrentMode.ToString() );
switch (currentMode)
{
case ColorModes.red:
break;
case ColorModes.green:
break;
case ColorModes.blue:
break;
}
}
Jack Jackson
3/18/2008 5:12:01 PM
On Tue, 18 Mar 2008 21:25:55 -0000, Jon Skeet [C# MVP]
[quoted text, click to view]

One further comment. You defined ColorMode with the [Flags]
attribute, indicating that you expect to set more than one value at at
time. Your switch cases will only execute if there is a single color
flag set. It isn't clear if that is what you intend.

As Jon said, it's a really good idea to tell us how it doesn't work
Jon Skeet [C# MVP]
3/18/2008 9:25:55 PM
[quoted text, click to view]

In what way is it not working?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.


One comment - why are you taking a property which is already the right
type (CurrentMode), then converting the value to string and parsing it
back to the same type? Just use:

switch (CurrentMode)

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
coconet
3/19/2008 10:53:36 AM
Problem solved. Sorry for the interruption.
Thanks.
AddThis Social Bookmark Button