Can you use Enum for double variables?

I created a class to handle Unit Conversion in C #. It does not work, since it should only return strings.

Here is the class:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace RestaurantManagementSystem { class unitHandler { public enum Units { Grams = 1, KiloGrams = 0.001, Milligram = 1000, Pounds = 0.00220462, Ounces = 0.035274, Tonnes = 0.000001, Litres = 1, Millilitres = 1000, Cups = 4.22675, FluidOunces = 33.814, TeaSpoon = 202.884, TableSpoon = 67.628, CubicFeet = 0.0353147, CubicInch = 61.0237, CubicCentimetres = 0.0001, CubicMetres = 0.001 } public double Convert_Value(Units from, Units to, double quantity) { double converted_quantity = 0; double fromValue = quantity * Convert.ToDouble(from.ToString()); converted_quantity = fromValue * Convert.ToDouble(to.ToString()); return converted_quantity; } } } 

I would like the enumeration type to contain double conversion coefficient values ​​for each unit, and then use them to convert and return the converted value.

+4
source share
6 answers

No. The default type for enum is int or long , and you cannot use fractional numbers with it. You can use a structure or class with enum for double

 public struct Units { public const double Grams = 1; public const double KiloGrams = 0.001; public const double Milligram = 1000; public const double Pounds = 0.00220462; public const double Ounces = 0.035274; public const double Tonnes = 0.000001; // Add Remaining units / values } 

And use it like

 double d = Units.KiloGrams; 
+11
source

You cannot use float / double with enumerations. You may need to define constants.

 public const double KiloGrams = 0.001; 
+3
source

Nope

I tried to give this to Visual Studio:

 public enum Test : double { Hello, World } 

And he said:

Byte type, sbyte, short, ushort, int, uint, long or ulong is expected

+2
source

You can convert double to long using the BitConverter.DoubleToInt64Bits(double) method before manually and copy it to an enumeration of type long . Then you will need to convert the enum value back to double .

This is probably more of a problem than worth it.

+1
source

Sorry can not be done. Enumerations are strictly integers / bytes. Indeed, they must be their own type.

You can try:

 enum Units() { Grams , KiloGrams , Milligram } public function GetUnitsFloatValue(Units unit) : float { switch (unit) { case Units.Grams : return 1; case Units.KiloGrams : return 0.001; case Units.MilliGrams: return 1000; } //unhandled unit? return 0; } 
+1
source

You cannot use double enumeration. You can use it only with int and long

0
source

All Articles