Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
C# Covariance / Contravariance in IEnumerable<T> where T is generic type, interface vs class

does someone understand why having a generic where constraint as class is different than interface? This code does not compile:

public interface IInterface
{
}

public class Class<T> where T : IInterface
{
    public void Do()
    {
        IEnumerable<IInterface> ret = GetEnumerable();
    }

    public IEnumerable<T> GetEnumerable()
    {
        return new T[0];
    }
}

whereas, by changing IInterface to class, suddenly compiles

public class IInterface
{
}

public class Class<T> where T : IInterface
{
    public void Do()
    {
        IEnumerable<IInterface> ret = GetEnumerable();
    }

    public IEnumerable<T> GetEnumerable()
    {
        return new T[0];
    }
}

I know that I can use:

IEnumerable<IInterface> ret = (IEnumerable<IInterface>)GetEnumerable();

but I really would like to know the reason why is the cast necessary if IInterface is interface.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The real question is, is it really necessary?

T, in this specific case, should always be a class.

You can ensure that by additionally adding the class constraint.

public interface IInterface
{
    bool Foo { get; set; }
}

public class Class<T> where T : class, IInterface
{
    public void Do()
    {
        var ret = GetEnumerable();

        foreach (var item in ret)
        {
            item.Foo = true; // you can handle the object just if you would have an object of that type.
        }
    }

    public IEnumerable<T> GetEnumerable()
    {
        return new T[0];
    }
}

Now if you remove the class constraint it would still work. However, if you hover over the squigglies of that item.Foo = true it will come apparent why:

enter image description here

over 4 years ago · Santiago Trujillo Relatório

0

As stated in the documentation:

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

With your interface example, there is no such constraint on T, whereas with the class example this constraint is inferred.

If you need to constrain to an interface, an additional "reference type constraint" is required:

public class Class<T> where T : class, IInterface
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda