Enum safety when casting from int

M

Matt

Hi,

Recently we had some code like this cause a failure:

MyEnum myEnum = (MyEnum) (int) dt[row][field];

i.e. reading an int out of the database and casting it into a
type-safe enum.

The thought behind this construct was to enforce type safety and
detect data corruption, which it only partly succeeded in doing.

The bug in our code was that that the wrong field was read from the
datatable, and this allowed an int that was not a defined enum element
to be read instead.

I had thought that this would cause an InvalidCastException, but it
appears that it does not as this test code demonstrates:

class Class1
{
enum MyEnum
{
Zero,
One,
Two,
Three
}

[STAThread]
static void Main(string[] args)
{
MyEnum myEnumA = (MyEnum) 99;
MyEnum myEnumB = (MyEnum) 1;
Console.WriteLine(myEnumA.ToString());
Console.WriteLine(myEnumB.ToString());
Console.Read();
}
}

This produces the following output:

99
One

The bug was eventually caught by a switch that throws an exception on
the default case, so our code managed to enforce safety eventually :)

It's not really a problem now that we know about it, but it doesn't
seem to be very intuitive as standard behaviour, given that in other
respects enums *are* type-safe, and that Enum.IsDefined can be used to
test whether enum elements are defined or not -- it would be nice to
be able to choose to have that check done automatically, as I think it
would make for safer code.

I'd be interested to hear what others think of this enum behaviour.


Regards,

Matt
 
N

Nicholas Paldino [.NET/C# MVP]

Matt,

I think it is just fine, because if you enforced something like that,
then you couldn't do the following:

[Flags]
public enum BodyParts
{
Arms,
Legs,
Torso,
Head
}

// Define the body parts that I have:
BodyParts pobjParts = BodyParts.Arms | BodyParts.Legs | BodyParts.Torso |
BodyParts.Head;

// Later on, check to see what body parts the user has.
if ((pobjParts & BodyParts.Head) != 0)
// Tell the user.
Console.WriteLine("Nick has a head");

While the example is odd, I think it shows why you can't enforce that.
You will kill all the code that allows for combinations of enumerated values
(which is a concievable operation). In your case, I would have to define
every possible combination for the values in the enumeration. For four
values alone, I would have to define at least twenty-four more enumeration
values just for possible combinations of four elements.

This is why they didn't do it, IMO.

Hope this helps.
 
N

news.microsoft.com

BZZT WRONG.

for bitwise operations to work they need to be powers of 2 for INDIVIDUAL
setting and testing.

This is one of the design flaws in Flags atrtribute i dont like. there is no
way to specify increments in the Attribute.

Nicholas Paldino said:
Matt,

I think it is just fine, because if you enforced something like that,
then you couldn't do the following:

[Flags]
public enum BodyParts
{
Arms,
Legs,
Torso,
Head
}

// Define the body parts that I have:
BodyParts pobjParts = BodyParts.Arms | BodyParts.Legs | BodyParts.Torso |
BodyParts.Head;

// Later on, check to see what body parts the user has.
if ((pobjParts & BodyParts.Head) != 0)
// Tell the user.
Console.WriteLine("Nick has a head");

While the example is odd, I think it shows why you can't enforce that.
You will kill all the code that allows for combinations of enumerated values
(which is a concievable operation). In your case, I would have to define
every possible combination for the values in the enumeration. For four
values alone, I would have to define at least twenty-four more enumeration
values just for possible combinations of four elements.

This is why they didn't do it, IMO.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Matt said:
Hi,

Recently we had some code like this cause a failure:

MyEnum myEnum = (MyEnum) (int) dt[row][field];

i.e. reading an int out of the database and casting it into a
type-safe enum.

The thought behind this construct was to enforce type safety and
detect data corruption, which it only partly succeeded in doing.

The bug in our code was that that the wrong field was read from the
datatable, and this allowed an int that was not a defined enum element
to be read instead.

I had thought that this would cause an InvalidCastException, but it
appears that it does not as this test code demonstrates:

class Class1
{
enum MyEnum
{
Zero,
One,
Two,
Three
}

[STAThread]
static void Main(string[] args)
{
MyEnum myEnumA = (MyEnum) 99;
MyEnum myEnumB = (MyEnum) 1;
Console.WriteLine(myEnumA.ToString());
Console.WriteLine(myEnumB.ToString());
Console.Read();
}
}

This produces the following output:

99
One

The bug was eventually caught by a switch that throws an exception on
the default case, so our code managed to enforce safety eventually :)

It's not really a problem now that we know about it, but it doesn't
seem to be very intuitive as standard behaviour, given that in other
respects enums *are* type-safe, and that Enum.IsDefined can be used to
test whether enum elements are defined or not -- it would be nice to
be able to choose to have that check done automatically, as I think it
would make for safer code.

I'd be interested to hear what others think of this enum behaviour.


Regards,

Matt
 
M

Matt

Hi Nicholas,

Nicholas Paldino said:
I think it is just fine, because if you enforced something like that,
then you couldn't do the following:
[snip]

While the example is odd, I think it shows why you can't enforce that.
You will kill all the code that allows for combinations of enumerated values
(which is a concievable operation). In your case, I would have to define
every possible combination for the values in the enumeration. For four
values alone, I would have to define at least twenty-four more enumeration
values just for possible combinations of four elements.

I see what you're saying with regard to bitfield enums; as I
originally didn't know that enums could hold non-defined values, I had
simply been storing bitfields in a variable of the underlying type
rather than casting it back to the enum type. I'll cast them back now,
as it will add some more safety.

Anyway what I've done is to implement the following code that our
people can use when they're not using a bitfield enum and want to
ensure that the cast is to a defined element:

public static object EnumTranslate(System.Type enumType, int
enumValue)
{
if ( !Enum.IsDefined(enumType, enumValue) )
{
throw new ArgumentException( string.Format("The value '{0}' is
not defined in the enum '{1}'.", enumValue, enumType.ToString()) );
}

return Enum.ToObject(enumType, enumValue);
}

It is called in the following way:

MyEnum myEnumA = (MyEnum) EnumTranslate(typeof(MyEnum), myValue);


It is *significantly* slower than a straightforward cast due to the
call to Enum.IsDefined, but it's possible that the IsDefined check
could be compiled only in Debug builds if it turned out to be a
performance problem.

Any suggestions from the group for improvements to this code are
welcome.


Regards,

Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top