Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method where T is type1 or type2

Is there a way to declare a generic function that the generic type is of type1 or type2?

example:

public void Foo<T>(T number) { } 

Can I constraint T to be int or long

like image 712
gdoron is supporting Monica Avatar asked Dec 18 '11 15:12

gdoron is supporting Monica


People also ask

What does the T designation indicate in a generic class?

Generics appear in TypeScript code inside angle brackets, in the format < T > , where T represents a passed-in type. <T> can be read as a generic of type T .

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

Can a generic class have multiple constraints?

There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.

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.


2 Answers

For ReferenceType objects you can do

public void DoIt<T>(T someParameter) where T : IMyType {  } 

...

public interface IMyType { }  public class Type1 : IMyType { }  public class Type2 : IMyType { } 

For your case using long as parameter will constrain usage to longs and ints anyway.

public void DoIt(long someParameter) {  } 

to constrain to any value types (like: int, double, short, decimal) you can use:

public void DoIt<T>(T someParameter) where T : struct {  } 

for more information you can check official documentation here

like image 82
Adam Moszczyński Avatar answered Oct 13 '22 20:10

Adam Moszczyński


Although you could use a generic constraint to limit the type of each generic argument T, unfortunately there is none that would allow you to enforce at compile time whether T is type1 or type2.

Nor is there any way to enforce at compile time that your generic argument can only be of any primitive type (int, long, double, ...).

like image 21
Darin Dimitrov Avatar answered Oct 13 '22 21:10

Darin Dimitrov