Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with decimal values or some like this

Basically I want to define an enum with decimal values but this 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 add these constants in a combobox where the options to display should be the name of constants and SelectedItem should return the value (0, 0.5M, 1) or some like these. I know that it is possible but it is ugly.

With an enum I can do this easly: comboBox.DataSource = Enum.GetValues(typeof(MyEnum));

What is the best way to simulate an enum with my requirements?

like image 487
Cristhian Boujon Avatar asked Mar 20 '13 21:03

Cristhian Boujon


People also ask

Should enums be numbers?

Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

Can enums have float values?

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

Are enums bad?

Many people consider Enums as a code smell and an anti-pattern in OOPs. Certain books have also cited enums as a code smell, such as the following. In most cases, enums smell because it's frequently abused, but that doesn't mean that you have to avoid them. Enums can be a powerful tool in your arsenal if used properly.

Is enum value type or reference?

Enum is a reference type, but any specific enum type is a value type. In the same way, System. ValueType is a reference type, but all types inheriting from it (other than System. Enum ) are value types.


1 Answers

A dictionary may be a good choice.

Dictionary<string,decimal> could be a good candidate - letting you name the 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 only expose a getter by index, instead of the whole Dictionary<TKey,TValue> interface.

like image 73
Oded Avatar answered Oct 27 '22 12:10

Oded