Consider the following Generic class:
public class Custom<T> where T : string
{
}
This produces the following error:
‘string’ is not a valid constraint. A type used as a constraint must
be an interface, a non-sealed class or a type parameter.
Is there another way to constrain which types my generic class can use?
Also, can I constrain to multiple types?
E.G.
T can only be string, int or byte
is not allowed, because the only
Tthat meets that is:string(stringissealed) – making it rather pointless as a generic.no – unless you do that at runtime via reflection rather than in a constraint (the static constructor is one way to do that – throwing an exception if used incorrectly)
You might use something like
IEquatable<T>, but that doesn’t restrict it as much as you would like, so ultimately: no.Something you could do is access it via an overloaded factory: