Home > Software design >  C# - Is there an interface for math?
C# - Is there an interface for math?

Time:12-14

I was working on a matrix-class, in which i want to make som linear algebra functions. I want to have a generic type in the matrix, which you can do arithmetic operations with, since i want to make a class representing a fraction instead of using double, but i also wanna use double in the future. Like this:

class Temp<T>
    {
        T[,] matrix;
        // Example of a math-using function
        public T Sum()
        {
            T sum = matrix[0,0];
            for(int i = 0; i < matrix.GetLength(0); i  )
            {
                for(int j = 0; j < matrix.GetLength(1); j  )
                {
                    sum  = matrix[i, j]; // Error here
                }
            }
            return sum;
        }
    }

I thought that i could use something like where T : IMathable but i couldn't figure out what inheirentents it should have.

CodePudding user response:

Have you tried the documents?

There is a Math class, you can check if that's the one you want Math Class

you import it with

using System;

Please give me a feedback on that. If this one doesn't solve try to be more specific, mentioning the language that has the function you want can help us to help you.

CodePudding user response:

Yes, in .NET 7 / C# 11:

class Temp<T> where T : INumber<T>
{
    T[,] matrix;
    public T Sum()
    {
        T sum = matrix[0, 0];
        for (int i = 0; i < matrix.GetLength(0); i  )
        {
            for (int j = 0; j < matrix.GetLength(1); j  )
            {
                sum  = matrix[i, j];
            }
        }
        return sum;
    }
}
  • Related