I want to create a generic class that takes a type parameter and restrict that parameter to numeric types or more generally to any type upon which the increment operator ++ can be applied.
I know I can do the following to restrict to structs but obviously there are structs that aren't numeric types and for which the ++ operator is not supported. Can I do this in C#
class Example<T> where T : struct
{
//Implementation detail
}
Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
A Generic class can have muliple type parameters.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.
Unfortunately this is not possible (see here.) You can only constrain the type to:
class
or struct
Constraining types to have specific operators is a much-requested feature but I believe it will not be in C# 4 either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With