473,883 Members | 1,589 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Q: Why casting an enum?

Hi!

I have created an enum list like this:

enum myEnum : int
{
This = 2,
That,
NewVal = 10,
LastItm
}

When using the enum, why do i have to cast the value?

int aValue = (int)myEnum.Thi s;

should it not just do with...

int aValue = myEnum.That; ?

Regards

Martin Arvidsson
Nov 17 '05 #1
18 11395
Because a value of an enum-type is not a number.

"Visual Systems AB (Martin Arvidsson)" <ma************ **@vsab.net> schrieb
im Newsbeitrag news:u2******** *****@TK2MSFTNG P15.phx.gbl...
Hi!

I have created an enum list like this:

enum myEnum : int
{
This = 2,
That,
NewVal = 10,
LastItm
}

When using the enum, why do i have to cast the value?

int aValue = (int)myEnum.Thi s;

should it not just do with...

int aValue = myEnum.That; ?

Regards

Martin Arvidsson

Nov 17 '05 #2
Visual Systems AB (Martin Arvidsson) wrote:
Hi!

I have created an enum list like this:

enum myEnum : int
{
This = 2,
That,
NewVal = 10,
LastItm
}

When using the enum, why do i have to cast the value?

int aValue = (int)myEnum.Thi s;

should it not just do with...

int aValue = myEnum.That; ?

Regards

Martin Arvidsson


you *should* use
myEnum aValue = myEnum.This;

the enum is a separate type, not just a way to specify a list of integer constants.
So if you want to convert an enum value to an int, you have to cast ...

Hans Kesting
Nov 17 '05 #3
An enum is a class. See the Enum class in the .Net framework.

Normally you do not want to cast an enum to an int. And if you do, you have
to do so explicitly.\

Really, you should avoid assigning values to the enum. The compiler will do
this for you. (If you are trying to make a set of bit flags, be sure to use
the [Flags] attribute. See FlagsAttribute class.)

If is recommended that you would use an enum as follows:

myEnum theEnum = myEnum.That;
if (theEnum == myEnum.LastItm) {
// do something
}

switch (theEnum) {
case: myEnum.This:
// stuff
break;
case: myEnum.That:
// other stuff
break;
// {rest of valid enum values go here}
default:
throw new ArgumentExcepti on("Invalid value for theEnum was
specified", "theEnum");
}

Hope this helps...

Frisky

"Visual Systems AB (Martin Arvidsson)" <ma************ **@vsab.net> wrote in
message news:u2******** *****@TK2MSFTNG P15.phx.gbl...
Hi!

I have created an enum list like this:

enum myEnum : int
{
This = 2,
That,
NewVal = 10,
LastItm
}

When using the enum, why do i have to cast the value?

int aValue = (int)myEnum.Thi s;

should it not just do with...

int aValue = myEnum.That; ?

Regards

Martin Arvidsson

Nov 17 '05 #4
Frisky <Fr***********@ NorthPole.net> wrote:
An enum is a class. See the Enum class in the .Net framework.
Actually, an enum is a value type. Enum itself is a reference type, but
every enum is a value type.
Normally you do not want to cast an enum to an int. And if you do, you have
to do so explicitly.\
Agreed.
Really, you should avoid assigning values to the enum. The compiler will do
this for you.


That entirely depends on the situation. If the enum is mirroring
existing status codes, for example, you almost certainly *do* want to
assign values.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Jon,

You are absolutley correct, an enum is a value type. It derives from the
System.ValueTyp e. Bad segway into, look up the documentation under
System.Enum.

I don't have to mirror the values for an external system. All I have to do
is make sure I map the external system in and out.

But, it is not a hard fast rule. The example you gave in particular
instances might be the right way to go. I gave the example of using the enum
as a bit flags. Yep, you gotta use values here.

That is why I used the word "avoid".

Fari enough?

Frisky

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Frisky <Fr***********@ NorthPole.net> wrote:
An enum is a class. See the Enum class in the .Net framework.


Actually, an enum is a value type. Enum itself is a reference type, but
every enum is a value type.
Normally you do not want to cast an enum to an int. And if you do, you
have
to do so explicitly.\


Agreed.
Really, you should avoid assigning values to the enum. The compiler will
do
this for you.


That entirely depends on the situation. If the enum is mirroring
existing status codes, for example, you almost certainly *do* want to
assign values.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #6
Frisky <Fr***********@ NorthPole.net> wrote:
You are absolutley correct, an enum is a value type. It derives from the
System.ValueTyp e. Bad segway into, look up the documentation under
System.Enum.

I don't have to mirror the values for an external system. All I have to do
is make sure I map the external system in and out.

But, it is not a hard fast rule. The example you gave in particular
instances might be the right way to go. I gave the example of using the enum
as a bit flags. Yep, you gotta use values here.

That is why I used the word "avoid".

Fari enough?


I still think "avoid" is a bit too strong without any extra
qualification. I find I need to assign values as often as I don't. It's
probably just a matter of how strong each of us thinks the word
"avoid" is though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7
Actually, it's just my opinion. And it works very well for me and my teams.

I very seldom define any enum with numerical values.

Just goes to show there is more than one way to do things.

--
Frisky

Intellectuals solve problems; geniuses prevent them. ~ Albert Einstein
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Frisky <Fr***********@ NorthPole.net> wrote:
You are absolutley correct, an enum is a value type. It derives from the
System.ValueTyp e. Bad segway into, look up the documentation under
System.Enum.

I don't have to mirror the values for an external system. All I have to
do
is make sure I map the external system in and out.

But, it is not a hard fast rule. The example you gave in particular
instances might be the right way to go. I gave the example of using the
enum
as a bit flags. Yep, you gotta use values here.

That is why I used the word "avoid".

Fari enough?


I still think "avoid" is a bit too strong without any extra
qualification. I find I need to assign values as often as I don't. It's
probably just a matter of how strong each of us thinks the word
"avoid" is though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #8
Actually, it's just my opinion. And it works very well for me and my teams.

I very seldom define any enum with numerical values.

Just goes to show there is more than one way to do things.

--
Frisky

Intellectuals solve problems; geniuses prevent them. ~ Albert Einstein
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Frisky <Fr***********@ NorthPole.net> wrote:
You are absolutley correct, an enum is a value type. It derives from the
System.ValueTyp e. Bad segway into, look up the documentation under
System.Enum.

I don't have to mirror the values for an external system. All I have to
do
is make sure I map the external system in and out.

But, it is not a hard fast rule. The example you gave in particular
instances might be the right way to go. I gave the example of using the
enum
as a bit flags. Yep, you gotta use values here.

That is why I used the word "avoid".

Fari enough?


I still think "avoid" is a bit too strong without any extra
qualification. I find I need to assign values as often as I don't. It's
probably just a matter of how strong each of us thinks the word
"avoid" is though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #9
Frisky <Fr***********@ NorthPole.net> wrote:
Actually, it's just my opinion. And it works very well for me and my teams.

I very seldom define any enum with numerical values.

Just goes to show there is more than one way to do things.


I think it's more that it shows that different people have different
applications. There may well be no case where I would assign values and
you wouldn't, but I deal with a lot of situations where the actual
values are important and you don't.

Certainly I'd agree that there's little point in assigning values when
they're not needed - although if the enum is used by an assembly other
than the one in which it's defined, and the assemblies may need to be
changed independently, changing the contents of the enum without
recompiling the other assembly will lead to out-of-date values being
used unless the values are specified and always kept constant.

For instance, if you have Lib.cs:
public enum Bar
{
Hello,
There
}

compiled to Lib.dll

and Test.cs:
using System;

public class Test
{
static void Main()
{
Bar b = Bar.There;
Console.WriteLi ne (b);
}
}

Compile Test.cs against Lib.dll, and run it - it prints out "There".
Now change Bar.cs to add a new member (Foo) between Hello and There.
Compile just Bar.cs to get a new Lib.dll, rerun Test and it will print
out "Foo". That wouldn't happen if you'd assigned There a value
explicitly and kept it constant when changing the enum. Of course, this
isn't a problem in many situations, but I thought I'd mention it as
another potential reason for explicit numbering.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

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

Similar topics

3
7055
by: Rob Jackson | last post by:
HiI've got a struct, known by file A.c, which contains a pointer to struct B. Struct B is unknown by file A.c (it is declared in C.h), and contains a typedef enum, which is declared in a file B.h, which is included in file A.c (this is getting really confusing, I know!).I want to access the enum in file A.c, but don't want to include file C.h, for various reasons.I've tried casting the enum, but still get the error "Dereferencing pointer...
3
3017
by: Matt | last post by:
Hi, Recently we had some code like this cause a failure: MyEnum myEnum = (MyEnum) (int) dt; 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
2
5399
by: babylon | last post by:
I have an enum public enum MyEnum : int { X, Y } I have to do int a = (int) MyEnum.X; can i overload the operator or other means to do something like
4
1942
by: DKode | last post by:
I started using Enums to make my code more readable. Here is my ENUM: public enum EntryType : int { RegularHours = 1, Lunch = 2, Vacation = 3, Sick = 4, Personal = 5 }
1
281
by: Remco | last post by:
Hi, Let me try to simply explain my questions. I've created a portal site with different types of users, e.g. Portal Administrators and Normal Users. One base class SessionUser (has a enum field UserType) and for each type of user a inherited class like SessionMasterUser and SessionNormalUser.
0
1722
by: Greg | last post by:
Not sure if this is best place for this problem, but here it is. I have a project that is simply a C# class that interfaces with an IFilter. This is so I can retreive the text from Word docs. I'm able to use this DLL without any problems within my test windows app, but not within my windows service (that's when I receive the casting exception). Here's the code (sorry it's long): VB Function within windows app and windows service:
8
8621
by: kc | last post by:
I'm trying to pull data from a database that I have no control over the structure of. There's a members table with a column for the member's sex. It just stores the sex as M or F. I'd like to create an enum to store the sex. Is there a way that I can create a method in the Enum to convert M to Male and F to Female, or does this method have to exist in another class? Thanks for any help!
2
2491
by: NullQwerty | last post by:
Hey folks, So, I've got three enum types: enum enum1 enum enum2 enum enum3 And then I've got a function overloaded three times to accept each enum type: private void func(enum1 myenum){}
4
1994
by: mitdej | last post by:
Hi there, I have an several enum types that starts from a nunmber other than 0. For example: public enum InternalStatus { Pending = 1, Ported = 2, Suspended = 3 } I put this values in a int column of a MSSQL table.
4
1449
by: Rene | last post by:
If variance/covariance is not allowed in array of value types, why is the expression on the "Main" method run successfully (see snippet below)? I am missing something? Thank you. --------------------- class Program { enum Foo
0
9943
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9793
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
10750
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10419
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
9577
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
7974
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
5996
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4619
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
3
3237
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.