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
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 .
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.
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.
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.
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
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, ...).
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