6
votes

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?

1
I'm sorry, but why out T? Do you need that out? - Andre Calil
Why is T an out parameter from your Interface?? What are you trying to achieve? from my perspective that looks odd/wrong. - Xtian Macedo
@exacerbatedexpert yes it does. That's how Julien Lebosquain could give a correct answer. - Jon Hanna
@FrédéricHamidi thanks for the information! - Xtian Macedo

1 Answers

7
votes

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.