I\'m working on a small project with a few different types of arrays (e.g. double[]
, float[]
, int[]
. For verification / testing / sani
If taken the question literally, it would be useless to have an Array
constraint. It's the same as it's useless to have a ValueType
constraint, as it actually doesn't check whether you use a value type as a generic argument, but whether the type you are passing is assignable to ValueType
.
So you can pass even Array
as the generic argument and it's OK.
What is actually useful is to have an array contraint allowing any type that derives from Array
, but not Array
itself:
void Print<TArr>(TArr t) where TArr : array //or [*] or other fancy syntax
Where T
can be []
, [,]
, [,,]
, [,,,]
, and so on. The only over non-generic Array
parameter is that we know the element type of the array.
Another way to solve this is to create a custom Array<T>
class with implicit operator overloads of T[]
, T[,]
, T[,,]
etc.
Edit:
There is no way to achieve this even in CIL (currently), because int[,]
and Array
don't differ in any interfaces or constructors. We need where T : Array but not Array itself
contraint.
The appropriate syntax to do what you want is this:
void Print<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
}