C # class class operators do not work

I have a problem with a common one. When I try to use fewer operators in the generic, their call does not occur. But it works with the Equals method. This is some test class:

public class Test { public int i; static public Boolean operator ==(Test obj1, Test obj2) { Console.WriteLine("operator =="); return obj1.i == obj2.i; } static public Boolean operator !=(Test obj1, Test obj2) { Console.WriteLine("operator !="); return obj1.i != obj2.i; } public override bool Equals(object obj) { Console.WriteLine("operator equals"); return this == (Test)obj; } public override int GetHashCode() { Console.WriteLine("HashCode"); return 5; } } 

And the Checker class:

 public class Checker { public Boolean TestGeneric<T>(T Left, T Right) where T : class { return Left == Right; //not work override operators return Left.Equals(Right); //work fine } } 

Small testing:

 Test left = new Test() { i = 4 }; Test right = new Test() { i = 4 }; var checker = new Checker(); Console.WriteLine(checker.TestGeneric<Test>(left, right)); Console.ReadKey(); 

How can I use fewer statements in the Test class from the general?

+8
operators generics c #
source share
1 answer

Overloaded operators are static methods, so they are not involved in polymorphism; they are solved statically at compile time based on the known type of operands.

In a generic method, the compiler cannot know that T will be Test (since it may actually be something else), so it uses the most general definition == , which is a comparative comparison.

Note that if you add a constraint to the generic method to force T be Test or a subclass of Test , it will work as expected, but of course it will no longer work for other types ...

+11
source share

All Articles