MadsKirkFoged / EngineeringUnits

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

Add unary minus operator? #36

Closed mschmitz2 closed 8 months ago

mschmitz2 commented 9 months ago

Currently

var p = Pressure.FromBar(10);
// var minusP = -p; // Does not compile
var minusP = p * -1; // Workaround

I noticed you are using this workaround yourself, e.g. in Extensions.Abs, so I'm pretty sure I didn't miss something this time.

Would probably need to define something along the lines of (following your way of defining the regular operator-)

public class UnknownUnit
{
    // ...

    public static UnknownUnit operator -(UnknownUnit right)
    {
        return -right?.BaseUnit;
    }
}

and

public class BaseUnit
{
    // ...

    public static UnknownUnit operator -(BaseUnit right)
    {
        if ((object)right == null)
        {
            return null;
        }

        try
        {
            if (right.Unit.IsSIUnit())
            {
                return new UnknownUnit(-right.NEWValue, right.Unit);
            }

            return new UnknownUnit(-right.ConvertValueInto(right), right.Unit);
        }
        catch (OverflowException)
        {
            return new UnknownUnit(double.PositiveInfinity, -right.Unit);
        }
    }
}

What do you think?

MadsKirkFoged commented 9 months ago

I think it is a good idea! I didn't even know I could use the -operator that way but I like it!

I'll add it!

mschmitz2 commented 9 months ago

The above code is untested so please check, but I'm pretty sure I did something like this a couple of years ago

mschmitz2 commented 8 months ago

Working as expected after recent updates