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

Home Posts Topics Members FAQ

Casting a string to an enum

kc
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!

Nov 21 '05 #1
8 8621


kc wrote:
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?


There is. Although it can only convert strings into enum values with
*exactly* matching names. The syntax is a bit fiddly:

'somewhere, define the enum
Public Enum Sex
F
M
End Enum

'in a procedure:
Dim sFromDatabase As String = "M" 'for example
Dim sx As Sex
Try
sx = CType([Enum].Parse(GetType( Sex), sFromDatabase), Sex)
Catch argex As ArgumentExcepti on
'sFromDatabase was neither 'M' nor 'F'
End Try

The fiddly syntax is because Parse, being inherited from System.Enum,
returns an Object, which we must convert to a Sex (or whatever). The [
] round Enum in Enum.Parse is because Enum is a VB keyword, so we must
escape it with [ ] in order to refer to the System.Enum class.

--
Larry Lard
Replies to group please

Nov 21 '05 #2
Hi,

Enum.Parse() can parse a string to a enum member, but the string should
exactly match the enum member. If your case, if you have the enum defined
as:

Enum Sex
M
F
End Enum

then [Enum].Parse (GetType (Sex), "M") will get you Enum.M (after casting).

HTH.

"kc" <je******@gmail .com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
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!
Nov 21 '05 #3
kc
And I'm cool with that...... Except I'd really prefer:

Public Enum Sex
Male
Female
End Enum

rather than using M and F. I have this issue with abbreviations. ;-) So
can I get the enum to do the conversion from M to Male?

(At the moment, I'm resigned to having my Data Mapper doing it for me)

Nov 21 '05 #4
Nope.

"kc" <je******@gmail .com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
And I'm cool with that...... Except I'd really prefer:

Public Enum Sex
Male
Female
End Enum

rather than using M and F. I have this issue with abbreviations. ;-) So
can I get the enum to do the conversion from M to Male?

(At the moment, I'm resigned to having my Data Mapper doing it for me)
Nov 21 '05 #5
"kc" <je******@gmail .com> schrieb:
And I'm cool with that...... Except I'd really prefer:

Public Enum Sex
Male
Female
End Enum

rather than using M and F. I have this issue with abbreviations. ;-) So
can I get the enum to do the conversion from M to Male?


\\\
Public Enum SexDatabase
M = 0
F = 1
End Enum

Public Enum Sex
Male = SexDatabase.M
Female = SexDatabase.F
End Enum
..
..
..
Dim s As SexDatabase = SexDatabase.F
Dim Sex As Sex = CType(s, Sex)
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>
Nov 21 '05 #6
On 22 Jul 2005 09:41:56 -0700, kc wrote:
And I'm cool with that...... Except I'd really prefer:

Public Enum Sex
Male
Female
End Enum

rather than using M and F. I have this issue with abbreviations. ;-) So
can I get the enum to do the conversion from M to Male?

(At the moment, I'm resigned to having my Data Mapper doing it for me)


Add a second Enum.

Public Enum Sex
Male = 1
Female = 2
End Enum

Public Enum Sex2
M = 1
F = 2
End Enum

Dim sFromDatabase As String = "M" 'for example
Dim sx As Sex
Try
sx = CType([Enum].Parse(GetType( Sex2), sFromDatabase), Sex)
Catch argex As ArgumentExcepti on
'sFromDatabase was neither 'M' nor 'F'
End Try
Nov 21 '05 #7
Errata:
Public Enum SexDatabase
M = 0


It's better to use a value <> 0...

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>
Nov 21 '05 #8
Hi Herfried ! :O)
It's better to use a value <> 0...


Could explain that a little bit more ?

I may see two reasons why this is true, i just want to know if you have any
others and/or the same..

1. Any Enum type values has a default value of 0. That's why I usually set
the default member of the Enum with a value of 0 or create a "NotSet"
member.

2. I didn't test that much, but i've noticed that when you connect to a
WebService that exposes a Enum type (with FlagsAttribute) , the values
getting map to client (in the reference.vb file) does not always follow the
values on the server..

I mean if you have the following Enum exposed by the WS :
'***
<Flags()> _
Enum MyEnum
Val1 = 0
Val2 = 1
Val3 = 2
Val4 = 4
End Enum
'***

You get this on the client side :
'***
<Flags()> _
Enum MyEnum
Val1 = 1
Val2 = 2
Val3 = 4
Val4 = 8
End Enum
'***

Thanks for your input.

--
Best Regards
Yanick
Nov 21 '05 #9

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

Similar topics

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
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:
6
4621
by: Jason Larion | last post by:
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...
3
4999
by: Vincent Finn | last post by:
Hi, I am trying to write a generic function and it isn't behaving as expected. I want to avoid having to write custom convert functions for my enums so I want to convert to an int and cast to the enum, this wouldn't compile so I tried a few variations. The cast fails inside the generic function even though its valid. The code below is the simplest example of the problem I could think of, even casting int to int fails.
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
9944
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
9796
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,...
1
10860
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
10420
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
9583
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...
0
7134
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
5804
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
6002
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4620
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.