Decimal enum or some similar

Basically, I want to define an enumeration with decimal values, but that is not possible. An alternative is:

public static class EstadoRestriccion { public const decimal Valur1 = 0; public const decimal Value2 = 0.5M; public const decimal Value3 = 1; }; 

But I need to add these constants to the combobox, where the parameters for display should be the name of the constants, and SelectedItem should return the value (0, 0.5M, 1) or some of them. I know this is possible, but it is ugly.

With an enumeration, I can do this easily: comboBox.DataSource = Enum.GetValues(typeof(MyEnum));

What is the best way to model an enumeration with my requirements?

+4
source share
4 answers

Vocabulary may be a good choice.

Dictionary<string,decimal> can be a good candidate - letting you name values.

 var values = new Dictionary<string,decimal>(); values.Add("Value1", 0m); values.Add("Value2", 0.5m); values.Add("Value3", 1m); 

This can be wrapped in a class, so you can only show getter by index, and not the entire Dictionary<TKey,TValue> .

+5
source

How about a static readonly decimal array?

 public static readonly decimal[] myValues = new[] {0, 0.5M, 1}; 
+2
source

There is simply no way. enum accepts only integer values. The code you put is good.

There is a slight difference between const decimal and static readonly decimal . The first is a direct assessment; the compiler replaces the name with its value. On the contrary, readonly sets the code that refers to the field each time and outputs a value from it. You can observe why readonly used with reference types, while const cannot (expect for a string).

+1
source

You can change your class a bit:

 public class EstadoRestriccion { public static readonly EstadoRestriccion Value1 = new EstadoRestriccion("Value1", 0); public static readonly EstadoRestriccion Value2 = new EstadoRestriccion("Value2", 0.5M); public static readonly EstadoRestriccion Value3 = new EstadoRestriccion("Value3", 1); private static readonly EstadoRestriccion[] values = new EstadoRestriccion[] { Value1, Value2, Value3 }; private string name; private decimal value; private EstadoRestriccion(string name, decimal value) { this.name = name; this.value = value; } public static EstadoRestriccion[] GetValues() { return values; } public override string ToString() { return this.name; } }; 

And some decimal conversions and / or a change in value will be public.

+1
source

All Articles