Question

I'm unclear as to why the following code snippet isn't covarient?

  public interface IResourceColl<out T> : IEnumerable<T> where T : IResource {

    int Count { get; }

    T this[int index] { get; }

    bool TryGetValue( string SUID, out T obj ); // Error here?
    }

Error 1 Invalid variance: The type parameter 'T' must be invariantly valid on 'IResourceColl.TryGetValue(string, out T)'. 'T' is covariant.

My interface only uses the template parameter in output positions. I could easily refactor this code to something like

  public interface IResourceColl<out T> : IEnumerable<T> where T : class, IResource {

    int Count { get; }

    T this[int index] { get; }

    T TryGetValue( string SUID ); // return null if not found
    }

but I'm trying to understand if my original code actually violates covariance or if this is a compiler or .NET limitation of covariance.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top