473,726 Members | 2,142 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rationale behind int to enum casts

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
{
Red,
Green,
Blue
}

class Whatever
{
static void Main()
{
// The following cast succeeds although the
// value 42 does not exist.
Color color = (Color) 42;
Console.WriteLi ne( "{0}", color );
}
}

I believe it would make my and other peoples life easier if that cast
failed. Moreover, the framework does not even seem to offer a function
to implement this directly. I have to roll my own, using
Enum.IsDefined( ).

What is the rationale for this?

Thanks & Regards,

Andreas
Nov 15 '05 #1
21 4597
Try to look at IConvertible

"Andreas Huber" <ah****@gmx.net > schrieb im Newsbeitrag
news:3e******** *************** ***@posting.goo gle.com...
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
{
Red,
Green,
Blue
}

class Whatever
{
static void Main()
{
// The following cast succeeds although the
// value 42 does not exist.
Color color = (Color) 42;
Console.WriteLi ne( "{0}", color );
}
}

I believe it would make my and other peoples life easier if that cast
failed. Moreover, the framework does not even seem to offer a function
to implement this directly. I have to roll my own, using
Enum.IsDefined( ).

What is the rationale for this?

Thanks & Regards,

Andreas

Nov 15 '05 #2
Hi Andreas,

Your enum is really an int.
And the framework won't look if it is defined or not because of performance
issue.
Imagine this

enum Tubo
{
Alfa = 11,
Beta = 44
}

public void SomeMethod(int j)
{
int i = 5 * j;
Tubo t = (Tubo)i;
}

It would be a big performance hit if runtime checks if it is valid or not...

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"Andreas Huber" <ah****@gmx.net > wrote in message
news:3e******** *************** ***@posting.goo gle.com...
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
{
Red,
Green,
Blue
}

class Whatever
{
static void Main()
{
// The following cast succeeds although the
// value 42 does not exist.
Color color = (Color) 42;
Console.WriteLi ne( "{0}", color );
}
}

I believe it would make my and other peoples life easier if that cast
failed. Moreover, the framework does not even seem to offer a function
to implement this directly. I have to roll my own, using
Enum.IsDefined( ).

What is the rationale for this?

Thanks & Regards,

Andreas

Nov 15 '05 #3
On Wed, 26 Nov 2003 14:49:38 +0100, "Miha Markic" <miha at rthand com>
wrote:
It would be a big performance hit if runtime checks if it is valid or not...


Only if you constantly convert from int to enum which you shouldn't be
doing anyway because it defeats the point of having enums in the first
place. At least in debug mode, the compiler or framework should check
automatically that the value is actually valid.

Again, the whole point of using enums instead of ints is type safety.
I agree with Andreas that this behaviour is bizarre and should be
fixed, performance hit or not.
--
http://www.kynosarges.de
Nov 15 '05 #4
Hi,

"Christoph Nahr" <ch************ @kynosarges.de> schrieb im Newsbeitrag
news:po******** *************** *********@4ax.c om...
On Wed, 26 Nov 2003 14:49:38 +0100, "Miha Markic" <miha at rthand com>
wrote:

I agree with Andreas that this behaviour is bizarre and should be
fixed, performance hit or not.


There is nothing to "fix". This is a documented behaviour.

From MSDN:
MSDN .NET Framework General Reference
Value Type Usage Guidelines

<quote>
Do not assume that enum arguments will be in the defined range. It is valid
to cast any integer value into an enum even if the value is not defined in
the enum. Perform argument validation as illustrated in the following code
example.
[Visual Basic]
Public Sub SetColor(newCol or As Color)
If Not [Enum].IsDefined(GetT ype(Color), newColor) Then
Throw New ArgumentOutOfRa ngeException()
End If
End Sub
[C#]
public void SetColor (Color color)
{
if (!Enum.IsDefine d (typeof(Color), color)
throw new ArgumentOutOfRa ngeException();
}
</quote>

hth
Uwe
Nov 15 '05 #5
Enums are used both for a set of enumerated values, and for bit fields. In
the bit fields case, you need to be able to represent values that aren't
equal to one of the defined constants.

You can use the static methods on the Enum class to see if a specific value
is equal to one of the predefined constant values.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"Andreas Huber" <ah****@gmx.net > wrote in message
news:3e******** *************** ***@posting.goo gle.com...
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
{
Red,
Green,
Blue
}

class Whatever
{
static void Main()
{
// The following cast succeeds although the
// value 42 does not exist.
Color color = (Color) 42;
Console.WriteLi ne( "{0}", color );
}
}

I believe it would make my and other peoples life easier if that cast
failed. Moreover, the framework does not even seem to offer a function
to implement this directly. I have to roll my own, using
Enum.IsDefined( ).

What is the rationale for this?

Thanks & Regards,

Andreas

Nov 15 '05 #6
On Wed, 26 Nov 2003 17:23:15 +0100, "Uwe Hafner"
<Sp********@NOS PAM.de> wrote:
There is nothing to "fix". This is a documented behaviour.


Yes... we disagree with that documented behaviour, and consider it
broken, hence we want a "fix".
--
http://www.kynosarges.de
Nov 15 '05 #7
On Wed, 26 Nov 2003 12:54:03 -0800, "Eric Gunnerson [MS]"
<er****@online. microsoft.com> wrote:
Enums are used both for a set of enumerated values, and for bit fields. In
the bit fields case, you need to be able to represent values that aren't
equal to one of the defined constants.


But bit field enums are always indicated by the [Flags] attribute,
correct? It should be easy enough to auto-generate a conversion check
if that attribute is not present.
--
http://www.kynosarges.de
Nov 15 '05 #8
Hi Chris,

"Christoph Nahr" <ch************ @kynosarges.de> wrote in message
news:id******** *************** *********@4ax.c om...
On Wed, 26 Nov 2003 12:54:03 -0800, "Eric Gunnerson [MS]"
<er****@online. microsoft.com> wrote:
Enums are used both for a set of enumerated values, and for bit fields. Inthe bit fields case, you need to be able to represent values that aren't
equal to one of the defined constants.


But bit field enums are always indicated by the [Flags] attribute,
correct? It should be easy enough to auto-generate a conversion check
if that attribute is not present.


Not really.
FlagsAttribute is just a descriptor - used by some function (for text output
(ToString) if I remember correctly).
You can safely use enums for flags without FlagsAttribute.

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com
Nov 15 '05 #9
Eric,
Enums are used both for a set of enumerated values, and for bit fields. In
the bit fields case, you need to be able to represent values that aren't
equal to one of the defined constants.


I know, I'm wondering why C# behaves this way __even if I don't put a
Flags attribute__ on my enum. This doesn't make a lot of sense to
me...

Thanks & Regards,

Andreas
Nov 15 '05 #10

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

Similar topics

2
2823
by: BillyO | last post by:
I need a general mechanism for passing parameters to an API function I am designing, call it foo. Foo processes data, the operation used to process the data and the parameters for that operation are to be passed to foo. A simple approach involves the use of base and derived classes: Class DataProcessor { Public: enum ProcessorTypeEnum{op1, op2, op3}
20
4848
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 EnumName FirstValue = 1 SecondValue = 2 ThirdValue = 3
12
3421
by: Steven T. Hatton | last post by:
Any opinions or comments on the following? I don't say it below, but I came out on the side of using enumerations over static constants. /* I'm trying to figure out the pros and cons of using static const * int class members as opposed to using enumerations to accomplish a * similar goal. The use of static constants seems more explicit and * obvious to me. Unless I assign values to the enumerators, the * compiler will do it for me....
2
4285
by: Voronkov Konstantin | last post by:
Thank you for answer, but I still did not got *how* to make serialization of enum type. Can you provide more instructions or hint, please? My task is to serialize enum to something like byte array, and then load enum from that byte array to the same enum type on other platform. One way to do I see is:
31
3608
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(); Control c = f; An enum value inherits from int but it doesn't get implicitly converted: HorizontalAlignment h = HorizontalAlignment.Center;
15
4374
by: Ben Hinkle | last post by:
I'm curious, what was the rationale for making a builtin type _Bool but then having #define true 1 #define false 0 in stdbool.h? That seems very odd that true and false don't have type _Bool. In particular I'm poking around with some language extensions to C and one of the most obvious extensions is overloading. Since "true" doesn't have type _Bool it makes overloading behavior with _Bool very odd. You'd think that at least it could be...
10
23602
by: kar1107 | last post by:
Hi all, Can the compiler chose the type of an enum to be signed or unsigned int? I thought it must be int; looks like it changes based on the assigned values. Below if I don't initialize FOO_STORE to be, say -10, I get a warning about unsigned comparison and I'm seeing an infinite loop. If I do initialize FOO_STORE = -10, I don't see any warnings. No infinite loop.
35
2846
by: dragoncoder | last post by:
Just a simple theoritical question to the experts. What was the rationale behind making STL containers follow copy semantics rather than reference semantics. References almost always make things easier without much of overhead. Then why not reference ? Thanks /P
1
1435
by: Nick Bastin | last post by:
I've done some searching in this newsgroup and on the internet and haven't found an answer, so I thought I'd ask here... :-) I don't understand why full specialization of a member function template in a class template is only valid if you fully specialize the class template as well. Consider the following example: template<class T, int ID> class RSMixin : public T
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9402
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9120
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8101
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
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 we have to send another system

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.