0

I have some Weights(ounces, grams and etc) but not sure how I should handle them. At first I was going to use an Enum and give each one an integer value and then store that value in my database(using EF)

I thought this would be a good idea as then I can do checks like

if(Measurement.Grams == usersChoice)
{
  // do something
}

It would also restrict the choices(ie if I don't support "stones" then it will fail if I try to set that in the enum),

I was going to then convert the Enums to an array and display it to the user but I ran into one problem "Fluid Ounce". I would have to display it as "FluidOunce".

I could use the Description Property but now I am not sure if this is the right way to go.

chobo2
  • 79,578
  • 183
  • 505
  • 811

1 Answers1

1

Option 1

Use enum Measurement and Dictionary<Measurement, string> to map from Measurement to the display name.

public enum Measurement
{
    Grams,
    FluidOunces,
    ...
}

private static Dictionary<Measurement, string> displayName = new Dictionary<Measurement, string>
{
    { Measurement.Grams, "Grams" },
    { Measurement.FluidOunces, "Fluid Ounces" },
    ...
};

public static string DisplayName(Measurement measurement)
{
    return displayName[measurement];
}

Option 2

Use class Measurement that has no public constructor, has public static readonly instances, and has properties.

public class Measurement
{
    public string DisplayName { get; private set; }
    private Measurement(string displayName)
    {
        this.DisplayName = displayName;
    }
    public static readonly Measurement Grams = new Measurement("Grams");
    public static readonly Measurement FluidOunces = new Measurement("Fluid Ounces");
    ...
}
Timothy Shields
  • 70,640
  • 17
  • 114
  • 164