Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to somehow define enum type as float or double in c#

Tags:

c#

enums

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 ?

like image 897
user310291 Avatar asked Dec 03 '11 21:12

user310291


People also ask

Can enum be float in C?

Enums can only be ints, not floats in C# and presumably unityScript.

Can an enum be a double?

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.

How do you define enum data type?

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.

Can an enum type have two values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.


2 Answers

Yes, you're stuck there. You can't use enums 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;
like image 59
Ry- Avatar answered Sep 16 '22 15:09

Ry-


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?

like image 37
Alan Avatar answered Sep 16 '22 15:09

Alan