Hi,
How can I create an enum of type double?
Is it possible or do I have to create some kind of collection and hash?
Hi,
How can I create an enum of type double?
Is it possible or do I have to create some kind of collection and hash?
Enum types have to be integral types, with the exception of char
. This doesn't include double
, so you'll need to make a lookup table or a set of constants.
You can't make it enum
http://msdn.microsoft.com/en-us/library/y94acxy2.aspx
One of possibilities:
public static class MyPseudoEnum{
public static readonly double FirstVal = 0.3;
public static readonly double SecondVal = 0.5;
}
I think byte, sbyte, short, ushort, int, uint, long, or ulong are your only options.
Why, as a matter of interest? Maybe we can work round it.
It is not possible to use double for an enum. See the following MSDN article for an explination of how enums work:
Here is a quote from the article that answers your question:
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int.
No, enums are essentially integer values.
I don't know about your particular problem you're solving but you could do a generic dictionary.
Of course, comparison of doubles is always fun, particularly when they differ way down in the decimals places. Might be interesting if you try to compare the results of a calculation (for equality) against a known double. Just a caution, if that is what you might need to do.
I guess it depends on how much trouble you want to go to. You can convert a double to a long, so if you converted your double values to long integers in a separate program, and output the constant values, you could then use them in your program.
I would strongly discourage this, by the way, but sometimes you gotta do what ya gotta do.
First, write a program to convert your doubles to longs:
Console.WriteLine("private const long x1 = 0x{0:X16}L;",
BitConverter.DoubleToInt64Bits(0.5));
Console.WriteLine("private const long x2 = 0x{0:X16}L;",
BitConverter.DoubleToInt64Bits(3.14));
Now, add that output to your program and create the enum:
private const long x1 = 0x3FE0000000000000L;
private const long x2 = 0x40091EB851EB851FL;
enum MyEnum : long
{
val1 = x1,
val2 = x2
}
When you want to test a double value against the enum, you'll have to call BitConverter.DoubleToInt64Bits()
, and cast the result to your enum type. To convert the other way, call BitConverter.Int64BitsToDouble()
.