Mike Twc
Mike Twc

Reputation: 2355

Is there a way to overload math function for a custom type?

I know you can do operator overloading (+-*/) for a custom type. Is there a way to do the same for custom math function as well? This would make vector operation more natural (like in R). Example:

vector = [1, 2, 3, 4, 5]

vector + vector = [2, 4, 6, 8, 10]  # can be achieved with operator overloading
vector * 5 = [5, 10, 15, 20, 25] # can be achieved with operator overloading

pow(vector, 2) = [ 1, 4, 9, 16, 25 ]  # is it possible in C#?

update
From the answers below I see that "function overloading" is not possible (probably doesn't make much sense) and the best way to handle that is to create custom math function library (static class).
That solution is fine, although is there a way to reuse "custom functions" with other custom types? Say I have numbers (int/float), complex numbers, vectors and matrices (array of vectors). I want my Pow function to work with all 4 types (it should power each numeric element in the object).
Also, is there a way to have function to do different things based on the input type? For example

abs(-1) = 1  # for integer abs just change the sign if negative
abs(4+3i) = sqrt(4^2+3^2) = 5 # smth different for complex number

Upvotes: 0

Views: 670

Answers (2)

BJ Myers
BJ Myers

Reputation: 6813

You can achieve something like this by utilizing the using static feature added in C# 6. This allows you to make static methods from a class available without having to specify the type name. (The .NET Math class is frequently cited as an example for this feature.)

Assuming a Vector class that implements IEnumerable<double>, you can create a class containing your static Pow function:

namespace Vectors
{
    public static class VectorMath
    {
        public static Vector Pow(Vector v, int exponent)
        {
            return new Vector(v.Select(n => Math.Pow(n, exponent)));
        }
    }
}

Then, in any code file where you want to use this class, include the statement

using static Vectors.VectorMath;

This will allow you to call the Pow method without needing to specify that it is a member of the VectorMath class:

class Program
{
    static void Main(string[] args)
    {
        Vector v = new Vector { 1, 2, 3 };
        Vector squares = Pow(v, 2);

        // Squares now contains [1, 4, 9]
    }
}

Upvotes: 2

MikkaRin
MikkaRin

Reputation: 3084

You can create extension method pow() for Array class

 public static class VecorExtension
{
        public static void pow(this Array vector, int i)
        {
            ...
        }
}

usage:

[1,2,3].pow(2);

Extension methods

Upvotes: 0

Related Questions