1

I have the following code:

public T[] Plus<T>(T[] a, T[] b, int size)
{
    T[] sum = new T[size];
    for (int i = 0; i < size; i++)
    {
        sum[i] = a[i] + b[i];
    }
    return sum;
}

but it does not work. How can I calculate "a" and "b" arrays?

P.S. T may be only sbyte int uint long ulong Sorry for my bad English.

Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
KAMAEL
  • 175
  • 2
  • 16
  • 1
    Generics does not support operators like `+`. There are ways do do it, but... – Marc Gravell Oct 03 '14 at 10:13
  • This might be of help http://stackoverflow.com/questions/9338398/how-to-sum-generic-numbers-in-c – apomene Oct 03 '14 at 10:15
  • This might be of help http://www.codeproject.com/Articles/8531/Using-generics-for-calculations – Christos Oct 03 '14 at 10:16
  • C# doesn't *have* "templates", btw – Marc Gravell Oct 03 '14 at 10:22
  • @MarcGravell Ok, in C# it called Generics, but I think that it makes no difference. – KAMAEL Oct 03 '14 at 10:34
  • @KAMAEL and I think it does (make a difference); "templates" and "generics" are very different concepts; C++ has "templates" - they are basically duck-typed overload generators; that is *not* what "generics" are. If you think of generics like templates, you are going to run into problems. – Marc Gravell Oct 03 '14 at 10:38

2 Answers2

3

This is a horrible way to do it, but it at least works:

    for (int i = 0; i < size; i++)
    {
        sum[i] = (dynamic)a[i] + (dynamic)b[i];
    }

It does, however, do a lot of boxing and unboxing. If you want a better version, you might do better by having overloads instead:

public static int[] Plus(int[] a, int[] b, int size)
{
    int[] sum = new int[size];
    for (int i = 0; i < size; i++)
    {
        sum[i] = a[i] + b[i];
    }
    return sum;
}
public static long[] Plus(long[] a, long[] b, int size)
{
    long[] sum = new long[size];
    for (int i = 0; i < size; i++)
    {
        sum[i] = a[i] + b[i];
    }
    return sum;
}

You could also still hack a generic version:

public static T[] Plus<T>(T[] a, T[] b, int size)
{
    switch(Type.GetTypeCode(typeof(T)))
    {
        case TypeCode.Int32:
            return (T[])(object)Plus((int[])(object)a, (int[])(object)b, size);
        case TypeCode.Int64:
            return (T[])(object)Plus((long[])(object)a, (long[])(object)b, size);
        // ...etc
        default:
            throw new NotSupportedException();
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

It is require that a and b both arrays must be of same type.