First, I must tell you that your idea of that ArrayCalc-class isn't a good use for a generic class. The main benefit of generics is that you can use exactly the same code for various types. If you have to make a case-distinction in your code between different types to make it work, that benefit is lost. In those cases it makes much more sense to implement the logic separately per type.
However, just to show you how your class could be implemented, here's my take:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int[] integers = new int[] { 10, 20, 30, 40 };
string[] strings = new string[] { "Himanshu", "Panjabi" };
ArrayCalc<int> calcInt = new ArrayCalc<int>();
int sum = calcInt.Add(integers);
Console.WriteLine(sum);
ArrayCalc<string> calcString = new ArrayCalc<string>();
string joined = calcString.Add(strings);
Console.WriteLine(joined);
}
public class ArrayCalc<T>
{
public T Add(T[] array)
{
if (array is int[])
{
int[] numbers = array as int[];
int sum = numbers.Sum();
return (T)(object)sum;
}
else if (array is string[])
{
string[] strings = array as string[];
string joined = String.Join("", strings);
return (T)(object)joined;
}
else
throw new NotSupportedException("can't add " + typeof(T).Name);
}
}
}
Console-output:
100
HimanshuPanjabi
As indicated by "UGLY!", this mis-use (to be honest) of generics where you make case-distinctions based on the generic type also leads to neccessary ugly reverse-casts to the generic type
T in order to be able to return the result without the compiler complaining about it.