0

I have a simple model class that holds values from a calculation, as doubles. Several properties are accessible, and I control the base unit, in this case I can guarantee they are in Millimeters for length, cubic millimeters for Volume and so on.

public class Model
{
    [MyDisplay(UnitsNet.Volume)]
    public double Volume { get; set; }
    [MyDisplay(UnitsNet.Length)]
    public double Length { get; set; }
}

I would like to annotate the properties with their type, so that in a display application, the user can choose the appropriate unit, i.e. all lengths in inches, all volumes in cubic feet. This display is configured at runtime, and I would like to offer the user a choice what unit they want to display the values in, based on the attribute.

What would the MyDisplayAttribute class look like? At runtime, I can get all the properties on my Model class, get the value of the attribute and convert the model value to the user chosen unit, but I'm lost on how to do that.

Krazykraut
  • 11
  • 2
  • If the units could be set at runtime by users, why don't you store it in an enum field? e.g. `public VolumnUnits VolumnUnit{get;set}` and define the `public enum VolumnUnits { CubicMillimeter, Litre, CubicMeter }` ? – MD Zand Dec 02 '22 at 12:00
  • That would be one way to go. The values in my model class are always in well defined units (i.e. millimeters for length, cubic millimeters for volume, radians for angle etc), so all I wanted was to give the UI editor a hint what types of unit (i.e. LengthUnit, VolumeUnit, AngleUnit) to offer the user to choose from. So in essence, because UnitsNet has different enum types for LengthUnit, VolumeUnit etc. I can't have an attribute that conveys that. No big deal, I can create my own, it's just a handful of unit types I need to handle. – Krazykraut Dec 02 '22 at 16:00

0 Answers0