473,507 Members | 2,387 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Enum safety when casting from int

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
Nov 15 '05 #1
3 2982
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]
- mv*@spam.guard.caspershouse.com

"Matt" <kt*******@sneakemail.com> wrote in message
news:55**************************@posting.google.c om...
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

Nov 15 '05 #2
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 [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:%2****************@TK2MSFTNGP09.phx.gbl...
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]
- mv*@spam.guard.caspershouse.com

"Matt" <kt*******@sneakemail.com> wrote in message
news:55**************************@posting.google.c om...
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


Nov 15 '05 #3
Hi Nicholas,

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in message news:<#3**************@TK2MSFTNGP09.phx.gbl>...
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
Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
4786
by: Glenn Venzke | last post by:
I'm writing a class with a method that will accept 1 of 3 items listed in an enum. Is it possible to pass the item name without the enum name in your calling statement? EXAMPLE: public enum...
6
796
by: James Brown | last post by:
Hi, I have the following enum declared: enum TOKEN { TOK_ID = 1000, TOK_NUMBER, TOK_STRING, /*lots more here*/ }; What I am trying to do is _also_ represent ASCII values 0-127 as TOKENs...
21
4571
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
4
5724
by: marc.gibian | last post by:
I have been trying to improve the quality of my C# and ADO.NET coding. One of the books I've read strongly advises against using string values to address individual values in DataRow objects. This...
31
3564
by: Michael C | last post by:
If a class inherits from another class, say Form inherits from control, then I can assign the Form to a variable of type Control without needing an explicit conversion, eg Form1 f = new Form1();...
34
11132
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code...
2
1300
by: SpotNet | last post by:
Hello NewsGroup, All the best for the New Year to you all. Have a question regarding enums and the integer types that can be scoped as. Briefly, if I scope an enum as uint, I cannot use the enum...
2
3503
by: JB | last post by:
Hi All, I'm pulling my hair over this and could really do with a bit of help. I'm using various different enums as bit fields and I'd like to create a set of generic Functions or Subs to...
11
6337
by: =?Utf-8?B?dG9iaXdhbl9rZW5vYmk=?= | last post by:
The following code is in a custom deserializer: object value = (int) 1; string nameToParse = Enum.GetName(field.FieldType, value); value = Enum.Parse(field.FieldType, nameToParse); Currently...
0
7223
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7111
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7485
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5042
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
1542
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
760
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
412
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.