473,804 Members | 3,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting String to User Defined Type

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
// is what I am trying to accomplish.
MyEnum ConvertedString = (MyEnum)MyStrin g;

Is there a way using the TYPE object or reflection to accomplish this goal?
I am a pretty advanced developer and understand most topics and commands,
so feel free to offer any ideas.

I know the example is silly and why would anyone do this, but
I am really trying to read these enum values from a text file and
assign them to a variable within a class I have, but it would have
clouded the question if I showed all of that code.
I hope the simple example is enough?

Thanks for any help.

Greg

Nov 17 '05 #1
5 5866
string MyString = "One";

MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString, true);
"gmccallum" wrote:
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
// is what I am trying to accomplish.
MyEnum ConvertedString = (MyEnum)MyStrin g;

Is there a way using the TYPE object or reflection to accomplish this goal?
I am a pretty advanced developer and understand most topics and commands,
so feel free to offer any ideas.

I know the example is silly and why would anyone do this, but
I am really trying to read these enum values from a text file and
assign them to a variable within a class I have, but it would have
clouded the question if I showed all of that code.
I hope the simple example is enough?

Thanks for any help.

Greg

Nov 17 '05 #2
Thank you so much. I don't know why I didn't even look for that when I knew
that Int32.Parse existed.
"SimonT" wrote:
string MyString = "One";

MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString, true);
"gmccallum" wrote:
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
// is what I am trying to accomplish.
MyEnum ConvertedString = (MyEnum)MyStrin g;

Is there a way using the TYPE object or reflection to accomplish this goal?
I am a pretty advanced developer and understand most topics and commands,
so feel free to offer any ideas.

I know the example is silly and why would anyone do this, but
I am really trying to read these enum values from a text file and
assign them to a variable within a class I have, but it would have
clouded the question if I showed all of that code.
I hope the simple example is enough?

Thanks for any help.

Greg

Nov 17 '05 #3
gmccallum wrote:
I am trying to convert the value of a string to a defined enum
value such as follows. Is there a way using the TYPE object
or reflection to accomplish this goal?


Unless I am completely misunderstandin g your question -- I think you are
looking for Enum.Parse().

http://msdn.microsoft.com/library/en...parsetopic.asp
--
Chris Priede (pr****@panix.c om)
Nov 17 '05 #4
Simon (et al),

I like your approach:
MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString, true);

But is there a way to make such a conversion if I can't explicitly
(hard-code) the Enum type into the statement?

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

"SimonT" wrote:
string MyString = "One";

MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString, true);
"gmccallum" wrote:
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
// is what I am trying to accomplish.
MyEnum ConvertedString = (MyEnum)MyStrin g;

Is there a way using the TYPE object or reflection to accomplish this goal?
I am a pretty advanced developer and understand most topics and commands,
so feel free to offer any ideas.

I know the example is silly and why would anyone do this, but
I am really trying to read these enum values from a text file and
assign them to a variable within a class I have, but it would have
clouded the question if I showed all of that code.
I hope the simple example is enough?

Thanks for any help.

Greg

Nov 17 '05 #5
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:81******** *************** ***********@mic rosoft.com...
Simon (et al),

I like your approach:
MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString,
true);

But is there a way to make such a conversion if I can't explicitly
(hard-code) the Enum type into the statement?

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

"SimonT" wrote:
string MyString = "One";

MyEnum ConvertedString = (MyEnum)Enum.Pa rse(typeof(MyEn um), MyString,
true);
"gmccallum" wrote:
> 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
> // is what I am trying to accomplish.
> MyEnum ConvertedString = (MyEnum)MyStrin g;
>
> Is there a way using the TYPE object or reflection to accomplish this
> goal?
> I am a pretty advanced developer and understand most topics and
> commands,
> so feel free to offer any ideas.
>
> I know the example is silly and why would anyone do this, but
> I am really trying to read these enum values from a text file and
> assign them to a variable within a class I have, but it would have
> clouded the question if I showed all of that code.
> I hope the simple example is enough?
>
> Thanks for any help.
>
> Greg
>

Nov 17 '05 #6

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

Similar topics

2
6810
by: Robert W. | last post by:
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(typeof(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...
7
5912
by: Desmond Cassidy | last post by:
Hi, I have being trying to get a grip of HTML data manipulation and am using the mshtml class and System.Net to retriver HTML pages. Now as far as I can see, one can read HTML in different ways. 1. Using the WebBrowser and loading the HTML into the mshtml.HTMLDocument class and then step through the various tags (input, a), tables etc. 2. Use System.Net.WebRequest/Response to load the data into a HTML string using a Stream Reader. Now...
7
7821
by: Sky | last post by:
I have been looking for a more powerful version of GetType(string) that will find the Type no matter what, and will work even if only supplied "{TypeName}", not the full "{TypeName},{AssemblyName}" As far as I know yet -- hence this question -- there is no 'one solution fits all', but instead there are several parts that have to be put together to check. What I have so far is, and would like as much feedback as possible to ensure I've...
4
1788
by: pmcgover | last post by:
I enjoyed Paul Barry's September article in Linux Journal entitled, "Web Reporting with MySQL, CSS and Perl". It provides a simple, elegant way to use HTML to display database content without any sql markup in the cgi script. The cgi script simply calls the Mysql command line with the HTML option (-H) and the SQL script file directed to that command. This provides complete separation of the markup from the sql code. The plain vanila...
2
4011
by: CoreyWhite | last post by:
Problem: You have numbers in string format, but you need to convert them to a numeric type, such as an int or float. Solution: You can do this with the standard library functions. The functions strtol, strtod, and strtoul, defined in <cstdlib>, convert a null- terminated character string to a long int, double, or unsigned long. You can use them to convert numeric strings of any base to a numeric
15
9672
by: allthecoolkidshaveone | last post by:
I want to convert a string representation of a number ("1234") to an int, with overflow and underflow checking. Essentially, I'm looking for a strtol() that converts int instead of long. The problem with strtol() is that a number that fits into a long might be too big for an int. sscanf() doesn't seem to do the over/underflow checking. atoi(), of course, doesn't do any checking. I've long thought it odd that there aren't strtoi() and...
21
55639
by: phpCodeHead | last post by:
Code which should allow my constructor to accept arguments: <?php class Person { function __construct($name) { $this->name = $name; } function getName()
1
6645
by: dishal | last post by:
Can anyone help me please? How do I convert these codes to launch from a JFrame instead of a Java Applet? A simple program where the user can sketch curves and shapes in a variety of colors on a variety of background colors. The user selects a drawing color form a pop-up menu at the top of the applet. If the user clicks "Set Background", the background color is set to the current drawing color and the drawing ...
3
1820
by: Dhananjay | last post by:
Hi All, I am facing problem when i am converting C#.net code(Delegate concept) into vb.net. I am unable to do that . Can someone help me to solve the problem. I am providing my C#.net code. ==================================my code is :- ====================================== static public List<MembershipUserWrapperGetMembers(bool
0
9704
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
9572
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
10562
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
10319
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
9132
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
7608
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
6845
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
5508
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...
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.