Considering a generic method, is there a possibility to set a constraint on the template type to have some specific properties?
In order to compile successfully the following code for example
public static int[] DoSomething<T> (T[] Input)
{
int[] Output = new int[Input.Length];
for (int i = 0;i < Input.Length;i++)
Output[i] = (int)Input[i].PropertyA+(int)Input[i].PropertyB;
return Output;
}
the template type needs to implement the PropertyA and PropertyB.
Is it possible somehow to set such a constraint on the template type?
EDIT:
And require in addition that PropertyA and PropertyB to be numeric types so they could be typed to int.
Thanks.
The only possibility is to define T as type derived from some well known base class or implementing well known interface:
Any your method will be:
Edit:
Creating generic method working with any numeric type but just with numeric types is imho not possible because .NET doesn’t have any base type like
Number. So you cannot limit generic type to numbers only. All numeric types are value types so you can do something like:But in such case your interface will accept any value type – any custom structure, char, bool, etc.