Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic constraint: Array of Structs

I would like to create a generic constraint that contains the type to be an array of value types (structs), something like:

public class X<T> where T : struct[]

or maybe

public class X<T, U>
    where U : struct
    where T : U[]

but this doesn't work. It seems System.Array cannot be used as type constraint.

So - how do I constrain a generic parameter to be an array of structs?

Updated after first answer:

public interface IDeepCopyable<T>
{
    T DeepCopy(T t);
}


public class DeepCopyArrayOfValueTypes<T> : IDeepCopyable<T>
    where T : is an array of value types
{
    T Copy(T t) {...}
}
like image 279
Wilbert Avatar asked Mar 12 '26 07:03

Wilbert


1 Answers

You don't need to.

Just constrain it to : struct, then write T[] instead of T when using the type parameter.

public class DeepCopyArrayOfValueTypes<T> : IDeepCopyable<T[]>
    where T : struct
{
    public T[] DeepCopy(T[] t) {...}
}
like image 82
SLaks Avatar answered Mar 14 '26 22:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!