473,771 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting of Enum values

When working with enums, I've noticed some behaviour that seems
completely counter-intuitive to me. I was wondering if someone here
could help restore my sanity, or at least help me to understand the
"why" of the behaviour.

After dimensioning an enum of type integer, any attribute referenced
seems to, by default, return the name of that attribute as a string,
instead of the integer value assigned to it.

The code snippet that follows demonstrates this behaviour.

Module enumtest

Private Enum Cheese As Integer
Cheddar = 1
Swiss = 2
Feta = 3
End Enum

Sub Main()
Debug.WriteLine (Cheese.Cheddar )
' "Cheddar" as System.String ...
' I expected "1" as System.Integer
'A More concrete example
Dim table As DataTable
Dim row As DataRow
Dim col As DataColumn
'Without DataType on column
table = New DataTable
col = New DataColumn

table.Columns.A dd(col)

row = table.NewRow()

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "Cheddar" as System.String

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
'With DateType on column
table = New DataTable
col = New DataColumn

col.DataType = GetType(System. Int32)
table.Columns.A dd(col)

row = table.NewRow

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

Exit Sub

End Sub

End Module
Thanks in advance for any help or insight that you can provice.

Regards,
Jason
MS DevEnv 2003 v7.1.3088
..NET Framework 1.2 v1.1.4322 SP1

Nov 21 '05 #1
6 4618
AFAIK, The debug.writeline will make a call to the ToString() method of the
object passed in. If you want to see the number try this.

Debug.WriteLine (Cint(Cheese.Ch eddar))

Didn't test it but it should write out the integer value of the enum.

Chris
"Jason Larion" <ja**********@g mail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
When working with enums, I've noticed some behaviour that seems
completely counter-intuitive to me. I was wondering if someone here
could help restore my sanity, or at least help me to understand the
"why" of the behaviour.

After dimensioning an enum of type integer, any attribute referenced
seems to, by default, return the name of that attribute as a string,
instead of the integer value assigned to it.

The code snippet that follows demonstrates this behaviour.

Module enumtest

Private Enum Cheese As Integer
Cheddar = 1
Swiss = 2
Feta = 3
End Enum

Sub Main()
Debug.WriteLine (Cheese.Cheddar )
' "Cheddar" as System.String ...
' I expected "1" as System.Integer
'A More concrete example
Dim table As DataTable
Dim row As DataRow
Dim col As DataColumn
'Without DataType on column
table = New DataTable
col = New DataColumn

table.Columns.A dd(col)

row = table.NewRow()

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "Cheddar" as System.String

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
'With DateType on column
table = New DataTable
col = New DataColumn

col.DataType = GetType(System. Int32)
table.Columns.A dd(col)

row = table.NewRow

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

Exit Sub

End Sub

End Module
Thanks in advance for any help or insight that you can provice.

Regards,
Jason
MS DevEnv 2003 v7.1.3088
.NET Framework 1.2 v1.1.4322 SP1

Nov 21 '05 #2
Debug.WriteLin e(Cint(Cheese.C heddar))

The only downside with that solution is that it could fail if the
enum's underlying type is (U)Long (which it isn't here but could be in
the general case). An alternative is to use

Cheese.Cheddar. ToString("d", Nothing)

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 21 '05 #3

"Mattias Sjögren" <ma************ ********@mvps.o rg> wrote in message
news:ur******** ******@TK2MSFTN GP15.phx.gbl...
Debug.WriteLi ne(Cint(Cheese. Cheddar))

The only downside with that solution is that it could fail if the
enum's underlying type is (U)Long (which it isn't here but could be in
the general case). An alternative is to use

Cheese.Cheddar. ToString("d", Nothing)


Or just Cheese.Cheddar. ToString("d")

The second parameter belongs to the another overloaded ToString() method and
doesn't need to be included :)

Ex:

Enum Cheese As Integer
Cheddar = 1
Swiss = 2
American= 3
End Enum

Public Sub Main()
Dim myFav As Cheese = Cheese.American
Console.WriteLi ne(myFav.ToStri ng("d"))
End Sub

Didn't test the above example, but I believe it's right ;)

Mythran
Nov 21 '05 #4
Chris (et al),

That's exactly the surprising behaviour... I would think that anything
that calls ToString on it would return a string-formatted object of the
_value_, not the attribute.

I.e., in the example. "1" as String. Why do I get the attribute as
string? That's the part that I'm struggling with.

Thanks,
--Jason
Chris, Master of All Things Insignificant wrote:
AFAIK, The debug.writeline will make a call to the ToString() method of the object passed in. If you want to see the number try this.

Debug.WriteLine (Cint(Cheese.Ch eddar))

Didn't test it but it should write out the integer value of the enum.

Chris
"Jason Larion" <ja**********@g mail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
When working with enums, I've noticed some behaviour that seems
completely counter-intuitive to me. I was wondering if someone here could help restore my sanity, or at least help me to understand the
"why" of the behaviour.

After dimensioning an enum of type integer, any attribute referenced seems to, by default, return the name of that attribute as a string, instead of the integer value assigned to it.

The code snippet that follows demonstrates this behaviour.

Module enumtest

Private Enum Cheese As Integer
Cheddar = 1
Swiss = 2
Feta = 3
End Enum

Sub Main()
Debug.WriteLine (Cheese.Cheddar )
' "Cheddar" as System.String ...
' I expected "1" as System.Integer
'A More concrete example
Dim table As DataTable
Dim row As DataRow
Dim col As DataColumn
'Without DataType on column
table = New DataTable
col = New DataColumn

table.Columns.A dd(col)

row = table.NewRow()

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "Cheddar" as System.String

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
'With DateType on column
table = New DataTable
col = New DataColumn

col.DataType = GetType(System. Int32)
table.Columns.A dd(col)

row = table.NewRow

row.Item(0) = Cheese.Cheddar
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

row.Item(0) = CInt(Cheese.Che ddar)
Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)

Exit Sub

End Sub

End Module
Thanks in advance for any help or insight that you can provice.

Regards,
Jason
MS DevEnv 2003 v7.1.3088
.NET Framework 1.2 v1.1.4322 SP1


Nov 21 '05 #5
"Jason Larion" <ja**********@g mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I would think that anything that calls ToString on it would return a
string-formatted object of the _value_, not the attribute.

Why do I get the attribute as string?
That's the part that I'm struggling with.


If you've gone to the trouble of defining an Enum, it's probably
because the "names" you've given to particular (or, more likely,
arbitrary) values are more "important" than the actual numerical
values themselves. After all, why not just use the numbers 1, 2,
3, etc. in your code? Because they're meaningless. "Cheddar",
"Swiss" and "Feta" enrich your code.

So it seems perfectly reasonable to me that calling ToString() on
an Enum value should give you the meaningful "name", rather than
some odd number "value".

Also, the "names" are more persistant. If you had, say, a Structure
containing values of your cheese Enum and saved it to a file, it
would [hopefully] save the Names, not the numerical values. Two
weeks down the line, you discover to your horror that you have to
redefine your Enum values. The "names" that you parse back out
of that file will /correctly/ map to their /new/ numerical values; if
you'd left the simple numbers in there, you'd be completely stuck.

HTH,
Phill W.
Nov 21 '05 #6
Jason,
In addition to the other comments:

The "Value" of the Enum IS the name!
> Private Enum Cheese As Integer
> Cheddar = 1
> Swiss = 2
> Feta = 3
> End Enum

The Cheese enum has 3 values: Cheddar, Swiss & Feta.

The fact that the Cheese.Cheddar value has a Integer representation of 1 is
an implementation detail, it could just as easily have a Byte representation
of 2 or a Long representation of
5,345,678,789,3 79,578 or even a Short representation of -5,789.

If you have a need for a constant Integer called Cheese with a value of 1,
then you may want to consider using a Constant instead!

Const Cheddar As Integer = 1
On a side note: IMHO Enum should support Char & String representations also,
but the designers of the framework did not have the foresight...

Hope this helps
Jay


"Jason Larion" <ja**********@g mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Chris (et al),

That's exactly the surprising behaviour... I would think that anything
that calls ToString on it would return a string-formatted object of the
_value_, not the attribute.

I.e., in the example. "1" as String. Why do I get the attribute as
string? That's the part that I'm struggling with.

Thanks,
--Jason
Chris, Master of All Things Insignificant wrote:
AFAIK, The debug.writeline will make a call to the ToString() method

of the
object passed in. If you want to see the number try this.

Debug.WriteLine (Cint(Cheese.Ch eddar))

Didn't test it but it should write out the integer value of the enum.

Chris
"Jason Larion" <ja**********@g mail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
> When working with enums, I've noticed some behaviour that seems
> completely counter-intuitive to me. I was wondering if someone

here > could help restore my sanity, or at least help me to understand the
> "why" of the behaviour.
>
> After dimensioning an enum of type integer, any attribute referenced > seems to, by default, return the name of that attribute as a string, > instead of the integer value assigned to it.
>
> The code snippet that follows demonstrates this behaviour.
>
> Module enumtest
>
> Private Enum Cheese As Integer
> Cheddar = 1
> Swiss = 2
> Feta = 3
> End Enum
>
> Sub Main()
>
>
> Debug.WriteLine (Cheese.Cheddar )
> ' "Cheddar" as System.String ...
> ' I expected "1" as System.Integer
>
>
> 'A More concrete example
> Dim table As DataTable
> Dim row As DataRow
> Dim col As DataColumn
>
>
> 'Without DataType on column
> table = New DataTable
> col = New DataColumn
>
> table.Columns.A dd(col)
>
> row = table.NewRow()
>
> row.Item(0) = Cheese.Cheddar
> Debug.WriteLine (row.Item(0)) ' "Cheddar" as System.String
>
> row.Item(0) = CInt(Cheese.Che ddar)
> Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
>
>
> 'With DateType on column
> table = New DataTable
> col = New DataColumn
>
> col.DataType = GetType(System. Int32)
> table.Columns.A dd(col)
>
> row = table.NewRow
>
> row.Item(0) = Cheese.Cheddar
> Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
>
> row.Item(0) = CInt(Cheese.Che ddar)
> Debug.WriteLine (row.Item(0)) ' "1" as System.Integer (Int32)
>
> Exit Sub
>
> End Sub
>
> End Module
>
>
> Thanks in advance for any help or insight that you can provice.
>
> Regards,
> Jason
>
>
> MS DevEnv 2003 v7.1.3088
> .NET Framework 1.2 v1.1.4322 SP1
>

Nov 21 '05 #7

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

Similar topics

3
3009
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
5392
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
18
11368
by: Visual Systems AB \(Martin Arvidsson\) | last post by:
Hi! I have created an enum list like this: enum myEnum : int { This = 2, That, NewVal = 10, LastItm
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
1718
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
8617
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!
3
3655
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
4
1292
by: PokerMan | last post by:
Hi guys, Maybe someone can explain thisi have this enum: public enum LimitType : int { BottomLimit, TopLimit, Limit }
4
1985
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.
0
10102
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...
1
10038
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9910
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
8933
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
7460
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
6712
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();...
1
4007
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
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.