Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this an invalid variance?

Exact code I'm trying to build:

    public interface IMapContainer<out T> where T : MapRoomBase
    {
        String GetName();

        IEnumerable<T> GetRooms();
    }

I'm getting this error: Invalid variance: The type parameter 'T' must be invariantly valid on 'MapLibrary.IMapContainer.GetRooms()'. 'T' is covariant.

I was under the impression that this would be valid since IEnumerable simply returns the items, and none can be added. Why is this not safe + valid?

like image 414
Erix Avatar asked Aug 13 '12 19:08

Erix


1 Answers

Make sure you're not targeting an old framework version. IEnumerable<T> is covariant starting with .NET 4. Your code compiles fine under .NET 4 and fails with the error you mention on .NET 3.5.

like image 169
Julien Lebosquain Avatar answered Oct 01 '22 21:10

Julien Lebosquain