473,587 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reflection - integer values directly to enum

The following code is in a custom deserializer:

object value = (int) 1;
string nameToParse = Enum.GetName(fi eld.FieldType, value);
value = Enum.Parse(fiel d.FieldType, nameToParse);

Currently we follow the path below:

intValue --enum name --enum value

Is there any way in reflection to do:

intValue --enum value

Jun 27 '08 #1
11 6372
tobiwan_kenobi wrote:
The following code is in a custom deserializer:

object value = (int) 1;
string nameToParse = Enum.GetName(fi eld.FieldType, value);
value = Enum.Parse(fiel d.FieldType, nameToParse);

Currently we follow the path below:

intValue --enum name --enum value

Is there any way in reflection to do:

intValue --enum value
You can cast to the enum from an int, can't you?

This scenario has always worked for me:
public enum TestEnum
{
One = 1,
Two
}

public TestMyEnum()
{
TestEnum a = (TestEnum)1;
TestEnum b = (TestEnum)2;

Console.WriteLi ne("A: " + a.ToString() + "\nB: " + b.ToString());
}
Chris.
Jun 27 '08 #2
Chris Shepherd <ch**@nospam.ch sh.cawrote:
intValue --enum value

You can cast to the enum from an int, can't you?
Only if you know the enum type at compile time - which it looks like
the OP doesn't.

Unfortunately Convert.ChangeT ype doesn't work, which was my first
thought. I suspect that using Expression.Conv ert would work with a bit
of work, but unfortunately dinner is calling me. Time for Marc to take
over, I'd say :)

(Seriously, there must be a better way, but I don't know it offhand...)

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #3
No, in this situation we can't cast because we are using reflection to write
a general routine that will create an instance of any enum that needs to get
deserialized, so we don't know which enum it is. The type of enum is
recovered from the XML document at deserialization time.

"Chris Shepherd" wrote:
tobiwan_kenobi wrote:
The following code is in a custom deserializer:

object value = (int) 1;
string nameToParse = Enum.GetName(fi eld.FieldType, value);
value = Enum.Parse(fiel d.FieldType, nameToParse);

Currently we follow the path below:

intValue --enum name --enum value

Is there any way in reflection to do:

intValue --enum value

You can cast to the enum from an int, can't you?

This scenario has always worked for me:
public enum TestEnum
{
One = 1,
Two
}

public TestMyEnum()
{
TestEnum a = (TestEnum)1;
TestEnum b = (TestEnum)2;

Console.WriteLi ne("A: " + a.ToString() + "\nB: " + b.ToString());
}
Chris.
Jun 27 '08 #4
tobiwan_kenobi wrote:
No, in this situation we can't cast because we are using reflection to write
a general routine that will create an instance of any enum that needs to get
deserialized, so we don't know which enum it is. The type of enum is
recovered from the XML document at deserialization time.

"Chris Shepherd" wrote:
>tobiwan_keno bi wrote:
>>The following code is in a custom deserializer:

object value = (int) 1;
string nameToParse = Enum.GetName(fi eld.FieldType, value);
value = Enum.Parse(fiel d.FieldType, nameToParse);

Currently we follow the path below:

intValue --enum name --enum value

Is there any way in reflection to do:

intValue --enum value
You can cast to the enum from an int, can't you?

This scenario has always worked for me:
public enum TestEnum
{
One = 1,
Two
}

public TestMyEnum()
{
TestEnum a = (TestEnum)1;
TestEnum b = (TestEnum)2;

Console.WriteLi ne("A: " + a.ToString() + "\nB: " + b.ToString());
}
Chris.
What about:

Object value = (int) 1;
value = Enum.Parse(fiel d.FieldType, value.ToString( ));

--
Lasse Vågsæther Karlsen
mailto:la***@vk arlsen.no
http://presentationmode.blogspot.com/
PGP KeyID: 0xBCDEA2E3
Jun 27 '08 #5
Found it. Too easy.

value = Enum.ToObject(f i.FieldType, value);
"tobiwan_kenobi " wrote:
The following code is in a custom deserializer:

object value = (int) 1;
string nameToParse = Enum.GetName(fi eld.FieldType, value);
value = Enum.Parse(fiel d.FieldType, nameToParse);

Currently we follow the path below:

intValue --enum name --enum value

Is there any way in reflection to do:

intValue --enum value
Jun 27 '08 #6


"Lasse Vågsæther Karlsen" wrote:
What about:

Object value = (int) 1;
value = Enum.Parse(fiel d.FieldType, value.ToString( ));
Besides not wanting to convert an int to a string to an enum for performance
reasons, it just doesn't work. We tried this and the above would give the
following:

1 --"1" --then fail (because "1" is not one of the names in the enum)
Jun 27 '08 #7
tobiwan_kenobi wrote:
>
"Lasse Vågsæther Karlsen" wrote:
>What about:

Object value = (int) 1;
value = Enum.Parse(fiel d.FieldType, value.ToString( ));

Besides not wanting to convert an int to a string to an enum for performance
reasons, it just doesn't work. We tried this and the above would give the
following:

1 --"1" --then fail (because "1" is not one of the names in the enum)

That's odd:

using System;

public class MyClass
{
public enum Test
{
A = 5,
B = 7,
C = 10,
D = 15
}

public static void Main()
{
for (Int32 index = 0; index <= 20; index++)
Console.WriteLi ne(index + " = " + Enum.Parse(type of(Test),
index.ToString( )));
Console.ReadLin e();
}
}

Tested this in Snippet Compiler on .NET 2.0 SP1 and 3.5, and both
produced the following:

0 = 0
1 = 1
2 = 2
3 = 3
4 = 4
5 = A <-- here
6 = 6
7 = B <-- here
8 = 8
9 = 9
10 = C <-- here
11 = 11
12 = 12
13 = 13
14 = 14
15 = D <-- here
16 = 16
17 = 17
18 = 18
19 = 19
20 = 20

As you can see, the enums corresponding to values are correctly parsed
from the string, even though the string is just a number.

In any case, if performance is an issue you won't gain much by mine or
your methods, in both cases you're involving a string.

You can only cast an int to an enum if you know the enum, if all you
have is a Type object, you need to muck about like you or I have done,
and if that doesn't produce fast enough code, well, you're out of luck.

However, let's put aside the current problem for a second.

What specifically is it that you're doing? If you're mucking around with
reflection and custom serialization, are you ultimately going to write
the value into a field or property of that enum type?

In other words, like this?

using System;
using System.Reflecti on;

public class MyClass
{
public enum Test
{
A = 5,
B = 7,
C = 10,
D = 15
}

public Test TestField = Test.D;

public static void Main()
{
MyClass mc = new MyClass();
FieldInfo fi = mc.GetType().Ge tField("TestFie ld");
fi.SetValue(mc, 5);
Console.WriteLi ne(mc.TestField );
Console.ReadLin e();
}
}

The output is A (which corresponds to the 5).

As you can see, I write the integer directly into the property. I assume
some conversion is taking place under the hood, but perhaps this has
less overhead than the code we've looked at so far?
Jun 27 '08 #8
Apparently it was different problem. We were reading the information in from
the database and were getting casting errors.

The SetValue using the value from the database was returning a casting
error. SetValue does not give me this error on the value returned from
Enum.ToObject. Since casting values from the database is very picky about
how it is done, Enum.ToObject seems to be the best choice.

"Lasse Vågsæther Karlsen" wrote:
tobiwan_kenobi wrote:

"Lasse Vågsæther Karlsen" wrote:
What about:

Object value = (int) 1;
value = Enum.Parse(fiel d.FieldType, value.ToString( ));
Besides not wanting to convert an int to a string to an enum for performance
reasons, it just doesn't work. We tried this and the above would give the
following:

1 --"1" --then fail (because "1" is not one of the names in the enum)

That's odd:

using System;

public class MyClass
{
public enum Test
{
A = 5,
B = 7,
C = 10,
D = 15
}

public static void Main()
{
for (Int32 index = 0; index <= 20; index++)
Console.WriteLi ne(index + " = " + Enum.Parse(type of(Test),
index.ToString( )));
Console.ReadLin e();
}
}

Tested this in Snippet Compiler on .NET 2.0 SP1 and 3.5, and both
produced the following:

0 = 0
1 = 1
2 = 2
3 = 3
4 = 4
5 = A <-- here
6 = 6
7 = B <-- here
8 = 8
9 = 9
10 = C <-- here
11 = 11
12 = 12
13 = 13
14 = 14
15 = D <-- here
16 = 16
17 = 17
18 = 18
19 = 19
20 = 20

As you can see, the enums corresponding to values are correctly parsed
from the string, even though the string is just a number.

In any case, if performance is an issue you won't gain much by mine or
your methods, in both cases you're involving a string.

You can only cast an int to an enum if you know the enum, if all you
have is a Type object, you need to muck about like you or I have done,
and if that doesn't produce fast enough code, well, you're out of luck.

However, let's put aside the current problem for a second.

What specifically is it that you're doing? If you're mucking around with
reflection and custom serialization, are you ultimately going to write
the value into a field or property of that enum type?

In other words, like this?

using System;
using System.Reflecti on;

public class MyClass
{
public enum Test
{
A = 5,
B = 7,
C = 10,
D = 15
}

public Test TestField = Test.D;

public static void Main()
{
MyClass mc = new MyClass();
FieldInfo fi = mc.GetType().Ge tField("TestFie ld");
fi.SetValue(mc, 5);
Console.WriteLi ne(mc.TestField );
Console.ReadLin e();
}
}

The output is A (which corresponds to the 5).

As you can see, I write the integer directly into the property. I assume
some conversion is taking place under the hood, but perhaps this has
less overhead than the code we've looked at so far?
Jun 27 '08 #9
tobiwan_kenobi wrote:
Apparently it was different problem. We were reading the information in from
the database and were getting casting errors.
Then you didn't have an int, you had something else.

This is why it is important for you to post everything you know about a
problem, or, to verify that the code you give us really exhibit the
problems you say it does.

Otherwise we'll post numerous answers or tips which really doesn't help
your real problem at all.

--
Lasse Vågsæther Karlsen
mailto:la***@vk arlsen.no
http://presentationmode.blogspot.com/
PGP KeyID: 0xBCDEA2E3
Jun 27 '08 #10

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

Similar topics

4
8353
by: Alicia | last post by:
Hi all, I have a problem with an Enum and Reflection. I am using an Xml and Reflection to create some controls, and to set their properties. All goes well until I encounter one property which is defined like this: public enum MyType { Alpha = 0, Beta = 1 }
8
2533
by: Eyeawanda Pondicherry | last post by:
I have put some code together that creates an enum dynamically from some database values. The enum can be read perfectly by an application that references the dynamically generated dll. If I /emit/ a new version of the assembly, and start the application again, the new values will appear for the enum. However, suppose I want the application to remain in a running state.
1
4665
by: Freddy Willockx | last post by:
Hi I'm doing some actions through reflection and generating some source code to speed up my actions. But, when I'm generating source code to read and write the fields of an Enum type, it goes wrong. An internal field "Value__" is added to the field. The problem is that this field is marked as public and not as private. Because this field is marked as public, my code generator assumes, he can
6
1197
by: ECathell | last post by:
I have a routine that compares 2 intances of the same object to see if there are any changes. The problem is that even though there are no changes, it tells me there are. I have even tried running a new routine that shows a messagebox with both objects' property values. below is my code. this is the actual comparison code: Dim Properties() As PropertyInfo = pType.GetProperties(BindingFlags.Public Or BindingFlags.Instance) Dim PropertyItem...
15
2140
by: Jeff Mason | last post by:
Hi, I'm having a reflection brain fog here, perhaps someone can set me on the right track. I'd like to define a custom attribute to be used in a class hierarchy. What I want to do is to have an attribute which can be applied to a class definition of a class which inherits from a base, mustinherit class. I want to define methods in the base class which will access the contents of the attribute as it is applied to
0
1273
by: IR | last post by:
Hi, I'm trying to store values of an enum type in a std::bitset container, in a contiguous manner. eg. typedef enum { meValue1 = 0xbaad, meValue2 = 0xbeef,
7
2617
by: John Goche | last post by:
Hello, The following program compiler and runs fine under gcc and produces the output 3. However, I am not sure whether such behavior is legal. In particular, as a related question, how would I go about checking that a supplied integer is contained within the set of values of an enumeration? Is there a way to do this? Thanks,
232
13195
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
4
3957
by: =?Utf-8?B?SmFzb24gUmV5bm9sZHM=?= | last post by:
(using .net 2.0) Say you have a class structure like this: class Address .... end class class Person FirstName
0
7854
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
8349
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
8221
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
6629
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
5722
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
5395
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
3845
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...
1
2364
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
1
1455
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.