473,626 Members | 3,948 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting String to Enum Value

In a posting earlier this year I found a simple approach to convert a string
to a particular Enum value. The one line solution looked like this:

MyEnum ConvertedString = (MyEnum) Enum.Parse(type of(MyEnum), MyString, true);

This is fine if one wants to hardcode each and every Enum in an If-ElseIf or
Select-Case construct but I'm wondering if there's a way to do it generically?

I have a situation where I'm using reflection to set a value. Here is the
code I've successfully been using:
propInfo.SetVal ue(node.Obj, Convert.ChangeT ype(newval,
propInfo.Proper tyType, null), indexer);

This has worked perfectly for the basic user types (ex. string, bool, int,
etc.) but fails if I try to introduce a property that is defined with a type
of one of my Enums.

Any ideas?

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #1
2 6799
Just a shot in the dark here...

Since you have propInfo.Proper tyType, which is a System.Type, you should be
able to check System.Type.IsE num to see if the type in question is an
enumeration. Then, you may be able to parse based on that. Something to
the effect of (note: I didn't test this):

if(propInfo.Pro pertyType.IsEnu m)
{
object val = Enum.Parse(prop Info.PropertyTy pe, newVal);
propInfo.SetVal ue(node.Obj, val, indexer);
}
//Maybe need some else if's for different property types??
else
{
//your existing code:
propInfo.SetVal ue(node.Obj, Convert.ChangeT ype(newval,
propInfo.Proper tyType, null), indexer);

}
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message
news:19******** *************** ***********@mic rosoft.com...
In a posting earlier this year I found a simple approach to convert a
string
to a particular Enum value. The one line solution looked like this:

MyEnum ConvertedString = (MyEnum) Enum.Parse(type of(MyEnum), MyString,
true);

This is fine if one wants to hardcode each and every Enum in an If-ElseIf
or
Select-Case construct but I'm wondering if there's a way to do it
generically?

I have a situation where I'm using reflection to set a value. Here is the
code I've successfully been using:
propInfo.SetVal ue(node.Obj, Convert.ChangeT ype(newval,
propInfo.Proper tyType, null), indexer);

This has worked perfectly for the basic user types (ex. string, bool, int,
etc.) but fails if I try to introduce a property that is defined with a
type
of one of my Enums.

Any ideas?

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #2
Derrick,

Your shot in the dark was a good one! In addition to your change, I had to
enhance some code elsewhere but it was worth it. For now I am storing the
actual English enum values rather than their numeric equivalents. This
removes a layer of obfuscation, which will make troubleshooting and future
analysis much easier.

Thank you!

--
Robert W.
Vancouver, BC
www.mwtech.com

"Derrick" wrote:
Just a shot in the dark here...

Since you have propInfo.Proper tyType, which is a System.Type, you should be
able to check System.Type.IsE num to see if the type in question is an
enumeration. Then, you may be able to parse based on that. Something to
the effect of (note: I didn't test this):

if(propInfo.Pro pertyType.IsEnu m)
{
object val = Enum.Parse(prop Info.PropertyTy pe, newVal);
propInfo.SetVal ue(node.Obj, val, indexer);
}
//Maybe need some else if's for different property types??
else
{
//your existing code:
propInfo.SetVal ue(node.Obj, Convert.ChangeT ype(newval,
propInfo.Proper tyType, null), indexer);

}
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message
news:19******** *************** ***********@mic rosoft.com...
In a posting earlier this year I found a simple approach to convert a
string
to a particular Enum value. The one line solution looked like this:

MyEnum ConvertedString = (MyEnum) Enum.Parse(type of(MyEnum), MyString,
true);

This is fine if one wants to hardcode each and every Enum in an If-ElseIf
or
Select-Case construct but I'm wondering if there's a way to do it
generically?

I have a situation where I'm using reflection to set a value. Here is the
code I've successfully been using:
propInfo.SetVal ue(node.Obj, Convert.ChangeT ype(newval,
propInfo.Proper tyType, null), indexer);

This has worked perfectly for the basic user types (ex. string, bool, int,
etc.) but fails if I try to introduce a property that is defined with a
type
of one of my Enums.

Any ideas?

--
Robert W.
Vancouver, BC
www.mwtech.com


Nov 17 '05 #3

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

Similar topics

2
5749
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
5
5856
by: gmccallum | last post by:
I am trying to convert the value of a string to a defined enum value such as follows. public enum MyEnum { One, Two }; string MyString = "One"; // or even this is fine string MyString2 = "MyEnum.One"; // This doesn't work (obviously), but effectively this
9
7123
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
2
1871
by: Richy | last post by:
Hi, I have a class that exposes the Microsoft.DirectX.Direct3D.Compare property, which allows a drop-down list of values (such as Never, Always etc) to be selected via the propertygrid. I write the string value ("Never", "Always" etc) to an XML file, and when I read back the XML file and set the property I want to be able to set it via the string. This is my property: <TypeConverter(GetType(Microsoft.DirectX.Direct3D.Compare))> _
8
1930
by: tony | last post by:
Hello! I have below a for loop and a switch in the for loop. I have also a enum called colBlowStep with some values. I have also an array called m_columnBlowStep with some strings. All items in the array m_columnBlowStep is string because I have used ToString on each enum item as you can see. I want to use enum in the case statment in the switch. I know I can use string but I rather want to use enum.
6
34924
by: Rico | last post by:
Hello, I'm looking for a way to reference the string name of an enumerator. I know in VB.net you can do "MyEnum.ToString" and get the name instead of the integer value. Is there a way I can do something similar with an Enum created in Access? Alright, here is some air code to explain what I mean Public Enum MyEnum
2
10519
by: MikalE | last post by:
Hi, I'll try and explain my problem. I'm simulating an incoming event that in my application I get from a COM object. My problem is that I can't seem to figure out how to convert an object back to enum. Here is my simulated event that I in real life receive through a COM object. private void button1_Click(object sender, System.EventArgs e) {
10
6114
by: Doug | last post by:
I have an enum that will look kind of like this: private enum MyEnum { SomeValue = 0, AnotherValue = 1, ThirdValue = 2 }
4
1503
by: =?Utf-8?B?cmF5ZnVzaW9u?= | last post by:
I am storing Keys.Right in a string and I need to convert it to back to the Keys Enumeration so I can handle it correctly. How do I do this?
0
8266
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
8199
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
8638
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
8365
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
8505
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
7196
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
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
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.