Why can I compare an object with IEnumerable of these objects, but not List?

I just realized that I wrote code that I would expect to be invalid (in terms of syntax), but the compiler accepts.

For brevity, I recreated an example. For type:

private class MyType
{
}

Then I can compare the instance MyTypewith IEnumerable<MyType>:

var myCollection = new List<MyType> { };
var test = new MyType() == (IEnumerable<MyType>)myCollection;

I am surprised that I can compare two objects of different types. Even more interesting (at least interesting to me), if I delete the cast on IEnumerable, I can not compare it. Why is this so? A Listimplements IEnumerable, therefore, assuming that somewhere there is no comparative coefficient of equality (maybe incorrect), why is this not available for Listeither?

+4
source share
2

, , , . , , .

, , .

. False .

var test1 = new MyType() == (IEnumerable<MyType>)myCollection; // False
var test2 = new MyType() == new List<MyType>();                // Compile-time error
var test3 = new MyType() == (IComparable)5;                    // False

- == - . Equals , -, . , - , - .

+7

( 7.10.6 ). (== (object x, object y)), :

:

• , . , (§6.2.4) .

• - T, T - -, - null. T .

6.2.4 , :

:

• S T, S , S T.

-

var test = new MyType() == (IEnumerable<MyType>)myCollection;

, MyType IEnumerable<MyType>, . , MyType - , . , , string ( - ).

, , , , . , , .

+3

Source: https://habr.com/ru/post/1694175/


All Articles