473,806 Members | 2,717 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using enums in refleciton

Hi,
I am trying to parse some text into c# commands using reflection. I am
new to this so there may be a simpler way of doing things. Anyhow, the
below code works fine except for enums. PropHere is an array
containing the string name of the property I want to set and newValues
is an array containing the string representation of the value I want to
set the property to. I use the valueType array to cast the string
values to the appropriate type. Is there a way that I can use
Enum.parse or some other approach to cast a string to the appropriate
enum value, keeping in mind that the valueType array contains strings,
not actual enum objects.

PropertyInfo t3 = inpObject.GetTy pe().GetPropert y(propHere[i]);
object[] nullArray = new object[0];

switch (valueType[i])
{
case "float":
t3.SetValue(inp Object, float.Parse(new Values[i]),
nullArray);
break;
case "String":
t3.SetValue(inp Object, newValues[i], nullArray);
break;
case "int":
t3.SetValue(inp Object, int.Parse(newVa lues[i]),
nullArray);
break;
case "bool":
t3.SetValue(inp Object, bool.Parse(newV alues[i]),
nullArray);
break;
case "double":
t3.SetValue(inp Object, double.Parse(ne wValues[i]),
nullArray);
break;
}

Dec 29 '06 #1
3 1420
Hi,

You should use a TypeConverter for all of the conversions when one is
available that can perform the conversion:

TypeConverter converter = TypeDescriptor. GetConverter(t3 .PropertyType);

if (converter != null && converter.CanCo nvertFrom(typeo f(string)))
{
t3.SetValue(inp Object,
converter.Conve rtFromString(ne wValues[i]), null);
}

Enum returns an EnumConverter that can convert to/from strings. All of the
framework primitive types have specific converters as well, so your switch
statement won't be necessary.

--
Dave Sexton
http://davesexton.com/blog

<bs********@yah oo.comwrote in message
news:11******** **************@ n51g2000cwc.goo glegroups.com.. .
Hi,
I am trying to parse some text into c# commands using reflection. I am
new to this so there may be a simpler way of doing things. Anyhow, the
below code works fine except for enums. PropHere is an array
containing the string name of the property I want to set and newValues
is an array containing the string representation of the value I want to
set the property to. I use the valueType array to cast the string
values to the appropriate type. Is there a way that I can use
Enum.parse or some other approach to cast a string to the appropriate
enum value, keeping in mind that the valueType array contains strings,
not actual enum objects.

PropertyInfo t3 = inpObject.GetTy pe().GetPropert y(propHere[i]);
object[] nullArray = new object[0];

switch (valueType[i])
{
case "float":
t3.SetValue(inp Object, float.Parse(new Values[i]),
nullArray);
break;
case "String":
t3.SetValue(inp Object, newValues[i], nullArray);
break;
case "int":
t3.SetValue(inp Object, int.Parse(newVa lues[i]),
nullArray);
break;
case "bool":
t3.SetValue(inp Object, bool.Parse(newV alues[i]),
nullArray);
break;
case "double":
t3.SetValue(inp Object, double.Parse(ne wValues[i]),
nullArray);
break;
}

Dec 29 '06 #2
Awesome, thanks! I am not sure if I am phrasing this correctly but is
there any easy way for me to loop through all the objects starting with
the base object to get to the one that has the property I want to set.
For exampe say I have
baseObjectPerso n.arm.hand.inde xfinger.nail.le ngth=10 and I parse the
left hand side to
baseObjectPerso n.
arm
hand
etc. how do I recursively act on each object to get me to nail.length?
Thanks,
Bob

Dave Sexton wrote:
Hi,

You should use a TypeConverter for all of the conversions when one is
available that can perform the conversion:

TypeConverter converter = TypeDescriptor. GetConverter(t3 .PropertyType);

if (converter != null && converter.CanCo nvertFrom(typeo f(string)))
{
t3.SetValue(inp Object,
converter.Conve rtFromString(ne wValues[i]), null);
}

Enum returns an EnumConverter that can convert to/from strings. All of the
framework primitive types have specific converters as well, so your switch
statement won't be necessary.

--
Dave Sexton
http://davesexton.com/blog

<bs********@yah oo.comwrote in message
news:11******** **************@ n51g2000cwc.goo glegroups.com.. .
Hi,
I am trying to parse some text into c# commands using reflection. I am
new to this so there may be a simpler way of doing things. Anyhow, the
below code works fine except for enums. PropHere is an array
containing the string name of the property I want to set and newValues
is an array containing the string representation of the value I want to
set the property to. I use the valueType array to cast the string
values to the appropriate type. Is there a way that I can use
Enum.parse or some other approach to cast a string to the appropriate
enum value, keeping in mind that the valueType array contains strings,
not actual enum objects.

PropertyInfo t3 = inpObject.GetTy pe().GetPropert y(propHere[i]);
object[] nullArray = new object[0];

switch (valueType[i])
{
case "float":
t3.SetValue(inp Object, float.Parse(new Values[i]),
nullArray);
break;
case "String":
t3.SetValue(inp Object, newValues[i], nullArray);
break;
case "int":
t3.SetValue(inp Object, int.Parse(newVa lues[i]),
nullArray);
break;
case "bool":
t3.SetValue(inp Object, bool.Parse(newV alues[i]),
nullArray);
break;
case "double":
t3.SetValue(inp Object, double.Parse(ne wValues[i]),
nullArray);
break;
}
Dec 29 '06 #3
Hi Bob,

Your request doesn't make much sense though since if you know the type of
baseObjectPerso n then don't need reflection, just cast it instead. If you
don't know what the type of the object will be at runtime, but you're sure
that it has a property called Arm, of some type that has a property called
Hand, then you'll probably know what the class or interface of Arm, Hand,
Finger, Nail, etc. are so you won't need reflection for that either and can
just perform a simple cast:

PersonWithArm person = baseObjectPerso n as PersonWithArm;

if (person != null)
return person.Arm.Hand .IndexFinger.Na il.Length;
else
return 0;

If you don't know what the type of object baseObjectPerso n will be at
runtime and you don't know what classes or interfaces that it might be then
you should probably choose a better design. Regardless, you can get all of
the properties for baseObjectPerso n by calling the
baseObjectPerso n.GetType().Get Properties method. From the returned
PropertyInfo array choose the one that you need depending upon your
requirements. Although, it doesn't make sense to expect a property named
Arm on some arbitrary object since the odds of it actually existing are
quite bad :)

--
Dave Sexton
http://davesexton.com/blog

<bs********@yah oo.comwrote in message
news:11******** **************@ n51g2000cwc.goo glegroups.com.. .
Awesome, thanks! I am not sure if I am phrasing this correctly but is
there any easy way for me to loop through all the objects starting with
the base object to get to the one that has the property I want to set.
For exampe say I have
baseObjectPerso n.arm.hand.inde xfinger.nail.le ngth=10 and I parse the
left hand side to
baseObjectPerso n.
arm
hand
etc. how do I recursively act on each object to get me to nail.length?
Thanks,
Bob

Dave Sexton wrote:
>Hi,

You should use a TypeConverter for all of the conversions when one is
available that can perform the conversion:

TypeConverte r converter = TypeDescriptor. GetConverter(t3 .PropertyType);

if (converter != null && converter.CanCo nvertFrom(typeo f(string)))
{
t3.SetValue(inp Object,
converter.Conve rtFromString(ne wValues[i]), null);
}

Enum returns an EnumConverter that can convert to/from strings. All of
the
framework primitive types have specific converters as well, so your
switch
statement won't be necessary.

--
Dave Sexton
http://davesexton.com/blog

<bs********@ya hoo.comwrote in message
news:11******* *************** @n51g2000cwc.go oglegroups.com. ..
Hi,
I am trying to parse some text into c# commands using reflection. I am
new to this so there may be a simpler way of doing things. Anyhow, the
below code works fine except for enums. PropHere is an array
containing the string name of the property I want to set and newValues
is an array containing the string representation of the value I want to
set the property to. I use the valueType array to cast the string
values to the appropriate type. Is there a way that I can use
Enum.parse or some other approach to cast a string to the appropriate
enum value, keeping in mind that the valueType array contains strings,
not actual enum objects.

PropertyInfo t3 = inpObject.GetTy pe().GetPropert y(propHere[i]);
object[] nullArray = new object[0];

switch (valueType[i])
{
case "float":
t3.SetValue(inp Object, float.Parse(new Values[i]),
nullArray);
break;
case "String":
t3.SetValue(inp Object, newValues[i], nullArray);
break;
case "int":
t3.SetValue(inp Object, int.Parse(newVa lues[i]),
nullArray);
break;
case "bool":
t3.SetValue(inp Object, bool.Parse(newV alues[i]),
nullArray);
break;
case "double":
t3.SetValue(inp Object, double.Parse(ne wValues[i]),
nullArray);
break;
}

Dec 29 '06 #4

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

Similar topics

13
9558
by: SpaceCowboy | last post by:
I recently got into a discussion with a co-worker about using enums across a dll interface. He wanted to use chars instead, argueing that depending on compiler settings the size of an enum could change and lead to memory corruption. I didn't see how this was possible. He claims that if a dll built for a program is built with different compiler settings than the launcher program, the enum size could change. The only way I could figure...
2
2083
by: Faisal | last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't seem to find an appropriate Reflection method to access Enums within a class I would like to loop through the Enums in the 'Foo' Class retrieve the Enums 'Car' and 'House Public Class Fo Public Enum Ca For Chevrole Toyot
27
2748
by: Mark A. Gibbs | last post by:
i have been toying with the idea of making my enums smarter - ie, more in line with the rest of the language. i haven't tested it yet, but what i came up with is a template like this: template <typename Enum> class smart_enum { public: typedef Enum enum_type;
2
1796
by: SpotNet | last post by:
Hello CSharpies, Can Enums in C# be UInt32 Types, and not just Int32 Types. I have a lot of constant declarations that are UInt32 that I want to put in Enums to ease the use of Intellisence. I have them in structs for now, I thought I'd ask. Would IntPtr Enums push the bounds of a stupid question? Regarding a post a bit further down by Tom; ' What would you like to change in C# and .NET?'
4
5594
by: Martin Pritchard | last post by:
Hi, I'm working on a project that historically contains around 40 enums. In the database various fields refer to the int values of these enums, but of course ref integrity is not enofrced and when looking at the db we can't tell what the value in a field represents. The other problem is that our enums are currently all stored in a single class, which means that because of no visibility constraints the enums are often used out of context...
2
2885
by: Simon Elliott | last post by:
I have some legacy C++ code which requires some enums to be 1 or 2 bytes in size. I'd ideally like to be able to specify that a few carefully selected enums are a particular size. By default, g++ seems to create enums of 4 bytes in length, unless I use the -fshort-enums option. I don't much want to use this all or nothing approach in case it breaks library code etc, and there's no guarantee that other compilers have a comparable...
11
12563
by: Marc Gravell | last post by:
This one stumped me while refactoring some code to use generics... Suppose I declare an enum MyEnum {...} Is there a good reason why MyEnum doesn't implement IEquatable<MyEnum> ? Of course, I can cast a MyEnum instance down to the int / short whatever (since int implements IEquatable<int>), but I don't like doing that, as it feels a bit messy, and I am then propegating the things that know what the base represenation is...
4
3001
by: Jon Slaughter | last post by:
is there a simple way to "step" through enums? I have a button that I want to click and have it "cycle" through a set of states defined by enums but the only way I can think of doing this "properly" yet "ugly" is to test the state for each state. I know that enumes are not ordered but since they are "stored" as numbers they have an inherent ordering which can be used. I don't really care about the ordering though but just the ability to...
3
1561
by: =?Utf-8?B?Sm9uYXRoYW4gU21pdGg=?= | last post by:
I have a class as follows: class GamesConsole { public int iReference; public enum Maker {Nintendo, Sega, Sony, Panasonic} }
0
9719
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
9599
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
10624
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...
1
10374
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
10111
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
5546
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
5684
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
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
3853
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.