Mike
Mike

Reputation: 1324

Is this a good place to use a non-Integer for an Enum (against the usual recommendations)?

I am trying to set up an enum to hold sheet metal gauges (thicknesses). Right now I have:

using System.ComponentModel;
public enum Gauge
{
    [Description("24 Gauge")]
    G24 = 239,
    [Description("20 Gauge")]
    G20 = 359,
    [Description("18 Gauge")]
    G18 = 478,
    [Description("16 Gauge")]
    G16 = 598,
    [Description("14 Gauge")]
    G14 = 747
}

My question is: Does this seem like a good place to break the rule about not using non-integral types behind an enum?

The real world values are like .0239, .0359, .0478, etc. A floating point type would probably be very unreliable, but I was considering a Decimal type. Isn't it a 96 bit integer with the decimal place shifted behind the scenes? Would that should be a reliable value or am I just asking for trouble with this idea?

Upvotes: 0

Views: 135

Answers (2)

Marcel N.
Marcel N.

Reputation: 13976

If I understand correctly what you want to do, then you can use a class with implicit conversion from/to double:

public class Gauge
{
    [Description("24 Gauge")]
    public const double G24 = 0.239;
    [Description("20 Gauge")]
    public const double G20 = 0.359;
    [Description("18 Gauge")]
    public const double G18 = 0.478;
    [Description("16 Gauge")]
    public const double G16 = 0.598;
    [Description("14 Gauge")]
    public const double G14 = 0.747;

    private double Value { get; set; }

    private Gauge(Double d)
    {
        Value = d;
    }

    public static implicit operator Double(Gauge g)
    {
        return g.Value;
    }

    public static implicit operator Gauge(Double d)
    {
        return new Gauge(d);
    }
}

And you can use it like this:

Gauge g = Gauge.G14;
g = 0.43;
//and so on, you can pass it as parameter to methods, etc

Upvotes: 2

AlexD
AlexD

Reputation: 32576

Using values like .0239 are not allowed for enums.

See enum (C# Reference):

Every enumeration type has an underlying type, which can be any integral type except char.

...

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

Upvotes: 1

Related Questions