Sunday, March 24, 2013

Useful Things to Know, #430: Casting to an Enum

We’re all familiar with defining an Enum.  In C#, they look like this:

public enum States
{
    Open,
    InUse,
    Closed
}

It’s understood by most people that Enum values are an alternate way of representing numeric constants.  Sometimes this is made explicit, as in the following:

public enum States
{
    Open = 1,
    InUse  = 2,
    Closed = 3
}

So when you assign to a value of type States, Intellisense will offer you a choice of three values:  States.Open, States.InUse, and States.Closed.

Are those the only values a variable of type States can have?

Actually, no. 

You can assign any integer to variable of an Enum, regardless of whether it’s defined as one of the available constants.  With the example above, the following:

States state = (States) 35;

… would be perfectly fine. Neither the compiler nor the runtime prevent this from happening.

So if your code looked like this:

if(state == States.Open)
{ 
   // do something
}
else if (state == States.InUse)
{
   // do something else
}
else {
   // assume the value must be States.Closed
}

… you have a potential bug. 

Labels:

0 Comments:

Post a Comment

<< Home