Question

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?

Was it helpful?

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.

OTHER TIPS

Not sure what this "Where" is to which you are referring, but you can declare your generic function as

public T Calculate<T>(T x, T y) where T : IComparable<T>
{
    // do calculations
}

I believe int and double both implement IComparable<T>.

The constraints system in Generics is still pretty coarse grained. Its still a blunt tool with relatively few options to choose from. A much richer feature set for expressing constraints on type parameters will allow all sorts of sophisticated algos to be designed like pattern based programming etc.

If you only tell me that T is a shirt type that I am looking at ... there aint much I can do with it. But if T is not only a shirt but is actually worn by a hooter with some int[] properties with counts in upper 30's and certain events that I can subscribe to and handle with custom codes then I think it will make programming a little more fun and lively.

You can constrain your generic type parameter to be a struct. Struct represents a value type like int or double. Here's an example from the MSDN article:

public class MyClass<T> where T : struct 

{...}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top