I would like to convert T to T[] if it is an array.
static T GenericFunction<T>(T t)
{
if (t == null) return default(T);
if (t.GetType().IsArray)
{
//if object is an array it should be handled
//by an array method
return (T) GenericArrayFunction((T[])t);
}
...
}
static T[] GenericArrayFunction<T>(T[] t)
{
if (t == null) return default(T);
for (int i = 0 ; i < t.Length ; i++)
{
//for each element in array carry
//out Generic Function
if (t[i].GetType().IsArray())
{
newList[i] = GenericArrayFunction((T[])t[i]);
}
else
{
newList[i] = GenericFunction(t[i]);
}
}
...
}
Error If I try (T[])t
Cannot convert type ‘T’ to ‘T[]’
Error If I just try to pass t
The type arguments for method ‘GenericArrayFunction(T[])’ cannot be inferred from the usage. Try specifying the type arguments explicitly.
Just because
Tis an array type doesn’t mean that it’s also an array ofT. In fact, the only way that could happen would be forTto be something likeobject,Arrayor one of the interfaces implemented by arrays.What are you really trying to do? I suspect you want to find out the element type of the array, and then call
GenericArrayFunctionwith the appropriateT– but that won’t be the sameT, and you’ll need to call it with reflection, which will be somewhat painful. (Not too bad, but unpleasant.)I suspect you don’t fully understand C#/.NET generics – please give us more context about the bigger picture so we can help you better.
EDIT: The reflection approach would be something like this:
Note that this will still fail for rectangular arrays, which get even harder to cope with.