Why do I need to implement IComparable <T> to compare two values ββin a generic method?
I am wondering why such code does not work:
public static bool cmp <T> (T a, T b) { return a == b; } I assume that an IComparable constraint should be added to make it work (possibly CompareTo instead of == ). With a class constraint, links will be compared. With the restriction struct matching is not allowed, as well as without restrictions.
Could it be possible to resolve this type and compare the links in the case of passing the object and compare the values ββwhen passing the types of values?
There is a comment in the specification .
Take a look at paragraph 7.10.6:
The predefined equality operators of the reference type do not allow comparing operands of the value type. Therefore, if the struct type does not declare its own equality operators, matching values ββof this structure type is not possible.
Structures cannot be compared with == because this operator is not defined for each type of value.
Integer types, floats, decimals, Booleans and enumerations, and, of course, reference types are specified in the standard explicit form.
So this is not possible by design. And why?
It makes sense. Intuition tells us that the type of value should be compared by value. Thus, two value type variables are equal if they have the same content . Although a struct is a data block, it may contain references to objects. If these links are different but have the same meaning, what should be the result of such a comparison?
For instance:
public struct A { public string S; } A a; A b; aS = "Hello"; bS = "Hello world".Split(' ')[0]; //to avoid reusing the same reference, probably ;] var result = (a == b); What should be the answer? They are different binary, but the meanings are the same.
Always ValueType.Equals , overloaded from object.Equals , which is trying to solve this problem. It performs a comparison of values ββwhere possible, and a comparative comparison where not. But you must keep in mind that this makes the structure bloated. You have a default operation for each structure, which can take age. Thus, it is possible, but not as structural functionality as such.