Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrain type to allow addition/subtraction operations (+/-) in C#

Tags:

c#

types

Is this possible?

public interface Foo<TBar>
  where TBar : (can use the '+' and '-' operators)

Thanks.

like image 324
ken Avatar asked Apr 01 '11 16:04

ken


People also ask

What is the purpose of the interface constraint on a type parameter?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

Where is generic type constraint?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.

What is T type in C#?

T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type. Note.


1 Answers

You can create a type Foo that overloads those two operators and then constrain your generic type to it. You cannot however constrain your generic parameter to require that any arbitrary type overloads such operators on an ad-hoc basis.

like image 195
Kirk Woll Avatar answered Oct 26 '22 12:10

Kirk Woll