MadsKirkFoged / EngineeringUnits

Working with units made easy with automatic unit-check and converting between units
MIT License
41 stars 10 forks source link

Creating HowTo for creating custom units #40

Open MadsKirkFoged opened 8 months ago

MadsKirkFoged commented 8 months ago

This is a placeholder for this Task started in #19.

How should we create custom units? Does any of the code need to change for making it easier to create custom units?

MadsKirkFoged commented 8 months ago

22122bd - Just relaxed the restrictions on some methods from Internal to public in order for users to better create their customs units

MadsKirkFoged commented 7 months ago

I have started on a Wiki post about creating custom units. Could you try it out and see if you can get it to work? https://github.com/MadsKirkFoged/EngineeringUnits/wiki/Costume-units

mschmitz2 commented 7 months ago

Works for me. Obviously the 2nd method doesn't give you the getters and setter methods which I personally prefer using.

These can be added as extensions as well but it is more work. Note also that you have to use two different namespaces if you want to use the same name for the unit enum and the getter, as is the case for regular units..

Using your example, this would look like:

public static class LengthCostUnitExtensions
{
    // New unit
    public static readonly LengthCostUnit EuroPerMeter = new LengthCostUnit(CostUnit.Euro, LengthUnit.Meter);
}

public static class LengthCostExtensions
{
    // New getter
    public static double EuroPerMeter(this LengthCost lengthCost) => lengthCost.As(LengthCostUnitExtensions.EuroPerMeter);

    // New setter method
    public static LengthCost FromEuroPerMeter(double? EuroPerMeter)
    {
        if (!EuroPerMeter.HasValue)
        {
            return null;
        }

        return new LengthCost(EuroPerMeter.Value, LengthCostUnitExtensions.EuroPerMeter);
    }
}

It's not ideal since the getter is now a method instead of a property and the setter has to be called with the extensions namespace:

// ideally LengthCost lc = LengthCost.FromEuroPerMeter(30.0);
LengthCost lc = LengthCostExtensions.FromEuroPerMeter(30.0);

 // ideally Console.WriteLine(lc.EuroPerMeter);
Console.WriteLine(lc.EuroPerMeter());
mschmitz2 commented 7 months ago

Btw, was "Costume Units" in the wiki (both title and url) intended or a typo?