Direct comparisons of C # value types

I read the following expression regarding comparing C # value types in C # in depth, second edition several times.

p. 77,

If the type parameter has no restrictions (restrictions do not apply to it), you can use the operators == and! =, but only for comparison values ​​of this type with zero. You cannot compare two values ​​of type T with each other.

...

When the type parameter is limited by the value type, == and! = Cant can be used with it at all.

If I understand (I don’t think so), that’s correct, it basically tells me that you cannot use == or! = To compare two types of values. Why why?

It is better if a simple example can be given for this case. Can someone give me a little idea that the above paragraph is trying to convey?

+5
source share
2 answers

It just means that when limiting the type of value (second paragraph)

static bool TryToCompare<T>(T first, T second) where T : struct
{
    return first == second; // not legal
    return first.Equals(second); // legal
}

Without limiting the type of value in the generic expression, he also talks about it (first paragraph)

static bool TryToCompare<T>(T first, T second) 
{
    return first == second; // not legal
    return first == null; // legal
    return first.Equals(second); // legal
}

If you restrict to Treference type, you can avoid using==

static bool TryToCompare<T>(T first, T second) where T : class
{
    return first == second; // legal
    return first == null; // legal
    return first.Equals(second); // legal
}
+7
source

The objects are not comparable, because a comparison using == checks to see if the link is the same (memory address). Usually you use if (string1.Equals (string2)).

Something I don’t understand is that I saw circumstances in which == works with strings, and circumstances in which it is not.

0
source

All Articles