Search code examples
c#genericsinheritancegeneric-programming

Inheritance in generic types


Can anyone help me in using Where for generic types? I was trying to create a function which does ST with a number of type double or int, so I said it should be generic function. But when I try to assign a value to variables of that generic type, I can't because it's not a numerical type. Also, I can't use Where to inherit generic type from int or double data types.

Here is the code:
public static T[,] Unit(int n) where T : PROBLEM
{

    T[,] mat = new T[n, n];  

    for (int i = 0; i < n; i++)   
        mat[i, i] = (T)1;      

    return mat;

}

Can anyone help?


Solution

  • Unfortunately one of the shortcomings of C# is that you cannot easily make generic numerical algorithms. You can kind of hack around it, like using this example from MSDN:

    public abstract class BaseCalculator<T>
    {
       public abstract T Add(T arg1,T arg2);
       public abstract T Subtract(T arg1,T arg2);
       public abstract T Divide(T arg1,T arg2);
       public abstract T Multiply(T arg1,T arg2);
    }
    public class IntCalculator : BaseCalculator<int>
    {
       public override int Add(int arg1, int arg2)
       {
          return arg1 + arg2;
       }
       //Rest of the methods 
    } 
    

    But generally speaking the .Net libraries just have a separate implementation for this sort of thing rather than attempting to use generics.