Search code examples
c#.netgenerics

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


Solution

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