Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class with restricted Type parameter

Tags:

c#

types

generics

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
}
like image 750
RobV Avatar asked Jul 17 '09 13:07

RobV


People also ask

How many type parameters can be used in a generic class?

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.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

How do you indicate that a class has a generic type parameter?

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.

Which of the following generic constraints restricts the generic type parameter to an Object of the class?

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.


1 Answers

Unfortunately this is not possible (see here.) You can only constrain the type to:

  • Implement a specific interface or derive from a specific class
  • Be a class or struct
  • Have a parameterless constructor

Constraining types to have specific operators is a much-requested feature but I believe it will not be in C# 4 either.

like image 155
Matt Howells Avatar answered Oct 22 '22 11:10

Matt Howells