kardanna
kardanna

Reputation: 39

How to overload System.Math methods with custom type

I'm currently working on some custom type Unit I want other users to be able to do math operations with (sin, cos, ln, etc.).

What I want to do is to overload mathematical functions from System.Math to take Unit as arguments so when users code they don't have to use two different static methods (Math.Sin() and Unit.Sin()) from two classes to do math with doubles and Unit in the same expression. I want to keep it simple to whoever wants to use my class.

How to overload System.Math or is there any other ways to achieve my goal?

Upvotes: 3

Views: 228

Answers (2)

RobV8R
RobV8R

Reputation: 1076

Welcome to Stack Overflow. Thanks for your question.

As with most things ".Net" there's several ways to accomplish this. I'd use user defined conversion operators.

By using conversion operators, your Unit Type can be converted to other data types.

For example, if you want to perform Math.Sin using a a Unit, you would create an explict or implicit conversion operator.

public struct Unit
{
    private readonly double value;

    public Unit(double value)
    {
        this.value = value;
    }

    public static implicit operator double(Unit d) => d.value;
    public static explicit operator Unit(double b) => new Unit(b);
}

As a result Math.Sin(double) can now accept a Unit.

var unit = new Unit(1d);
var sin = Math.Sin(unit);
Console.WriteLine(sin.ToString(CultureInfo.InvariantCulture));

If this doesn't answer your question, please tell us more about the Unit Type. Feel free to paste your existing source into your original question.

Upvotes: 3

Logarr
Logarr

Reputation: 2417

Gabrik is right that you can't just overload System.Math. Another solution would be to completely wrap System.Math with your own class. Since I assume the primary issue with combining doubles and Unit is that Unit will need to have some form of conversion happen first, you would create overloads of some of the methods that would take in Unit as a parameter in any of the combinations that would be valid.

It may seem like more work than simply overloading particular methods, but the majority of the time consuming work will be the same as if that was possible. The remaining methods, which you wouldn't be overloading anyways, would simply call to the underlying method on System.Math. You could generate all that code through any number of techniques available for rapid code generation.

Upvotes: 0

Related Questions