tobiwan_kenobi said:
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.WriteLine(index + " = " + Enum.Parse(typeof(Test),
index.ToString()));
Console.ReadLine();
}
}
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.Reflection;
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().GetField("TestField");
fi.SetValue(mc, 5);
Console.WriteLine(mc.TestField);
Console.ReadLine();
}
}
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?