The fact is that with this declaration:
cmpStr<T>(string s, T c1, T c2)
arguments of any type can be passed to the method. In this case, all operations that are carried out in a method with arguments must be supported by the type of this argument. Does any type support operations <,>, <=,> =? No, not any. Therefore, this code is incorrect.
In order for the code to work, the type parameter Т
needs to impose a restriction: for Т
be of the type (or its subtype) that supports the operations you need. Alternatively, you can enter some type (for example, MyType
) in which these operations will be redefined. And then specify the limit:
cmpStr<T>(string s, T c1, T c2) where T : MyType
MyType
can be a wrapper:
public class MyType { public int Value; public static bool operator <(MyType a1, MyType a2) { return a1.Value < a2.Value; } public static bool operator >(MyType a1, MyType a2) { return a1.Value > a2.Value; } ... }
(At the same time, we encounter a new problem: Value
too, I want to make a generic, but it is impossible. A vicious circle.)
Also, MyType
may not be a wrapper, but contain its own logic.
That is the general answer. Clarify your task, and I will clarify the answer.
PS Finally, a couple of links to alternative solutions: https://stackoverflow.com/a/18875731/1985167 http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html