Why does the C# compiler allow an explicit cast between IEnumerable and TAlmostAnything?

I would suppose it’s because IEnumerable<T> is an interface where some implementation could have an explicit cast to Banana – no matter how silly that would be.

On the other hand, the compiler knows that List<T> can’t be explicitly cast to a Banana.

Nice choice of examples, by the way!

Adding an example to clarify. Maybe we’d have some “enumerable” that should always contain at most a single Banana:

public class SingleItemList<T>:Banana, IEnumerable<T> where T:Banana {
    public static explicit operator T(SingleItemList<T> enumerable) {
        return enumerable.SingleOrDefault();
    }

    // Others omitted...
}

Then you could actually do this:

IEnumerable<Banana> aBunchOfBananas = new SingleItemList<Banana>();
Banana justOneBanana = (Banana)aBunchOfBananas;

As it’s the same as writing the following, which the compiler is perfectly happy with:

Banana justOneBanana = aBunchOfBananas.SingleOrDefault();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)