It says here that the possible types for an enum
are byte
, sbyte
, short
, ushort
, int
, uint
, long
, or ulong
.
What if I need a float
or a double
to define percentage increments such as 1.5
or 2.5
for example? Am I stuck?
As said here: http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design
An enum is a structure with a set of static constants. The reason to follow this guideline is because you will get some additional compiler and reflection support if you define an enum versus manually defining a structure with static constants.
Since an enum is a set of constants, why can't I have float constants ?
Update: it is said here: http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design "Did you know that the CLR supports enums with an underlying type of float or double even though most languages don't choose to expose it?"
Since I'm only using c# is there a way to do so with some hacks ?
Enums can only be ints, not floats in C# and presumably unityScript.
Enums type can be an integer (float, int, byte, double etc.) but if you use beside int, it has to be cast. Enum is used to create numeric constants in . NET framework.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Yes, you're stuck there. You can't use enum
s with floating-point types. You can use a static class
with constants, however:
public static class MyFloatEnum {
public const float One = 1.0;
public const float OneAndAHalf = 1.5;
// etc.
}
And it will look somewhat close in IntelliSense. Alternatively, you may just want to use constants:
public const float A = 0.5;
public const float B = 17.62;
Although the CLR itself supports floating point enums, C# designers chose not to expose this in the language (see http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design). You can either use constants as in John Saunders' answer, or you can define an integer enum with multiplied values and then divide them back if/when you need the value.
The use case would be definitely interesting, though. Why do you need/want this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With