how we can do it(use operators in Generic Methods)
Generally, we can't. For most operators, if used with a type parameter (say T
), the compiler cannot work out an applicable overload to use at compile-time.
If you write user-defined operators on a base class (that is on a reference type that is non-sealed), you can use them if you have a constraint. For example System.Uri
is a non-sealed class that overloads the ==
operator. Then if you do:
class Test<T> where T : Uri
{
internal void Method(T x, T y)
{
bool ok = x == y;
}
}
the user-defined overload is used. Same with other operators, of course.
But generally you want to do this with pre-defined value types and pre-defined operators, for example T
is some numeric type (struct
), and you want ==
(equality) or *
(multiplication) or <<
(bit shift on integer) or similar. But that is not possible in C#.
It is possible to use dynamic
instead of generic types, but obviously that is entirely different.