I want to extend the IEnumerable class but only for types that can be operated (int, decimal, single and double).
Is this doable? I don’t see the way to restrict this:
public static class IEnumerableExtension
{
public static decimal FindBestSubsequence<T> (this IEnumerable<T> source, out int startIndex, out int endIndex)
{
}
}
Thanks in advance.
You’re looking for generic constraints but you can’t constrain a type parameter to only be valid for a specific set of types. The closest you could come would be something like:
… as those are all interfaces which each of those types implements. However, this wouldn’t prevent, say,
Int16from being used as the type argument. Do you definitely not want it to be applicable for anIEnumerable<short>? What would go wrong if it were used for that?You could have a set of non-generic public overloads, which then called to a constrained generic private method: