KAMAEL
KAMAEL

Reputation: 175

Need to add 2 number in c# genericclass

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.

Upvotes: 1

Views: 91

Answers (2)

Syed Muhammad Zeeshan
Syed Muhammad Zeeshan

Reputation: 1045

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

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063433

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();
    }
}

Upvotes: 3

Related Questions