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

185
Visualizações
nullable generic interface type for self referenceable entities
public class MyClass : ISelfReferenceable<Guid>
{
     public Guid Id {get;set;}
     public Guid? ParentId {get;set;}
}
public interface ISelfReferenceable<TId>
{
     TId Id {get;set;}
     TId? ParentId {get;set;}
}

Can anyone explain to me why the above does not work?

It shouts Compiler Error CS0738

'type name' does not implement interface member 'member name'. 'method name' cannot implement 'interface member' because it does not have the matching return type of ' type name'.

on MyClass.ParentId, saying that it doesn't implement ISelfReferenceable.ParentId, unless I change MyClass.ParentId from Guid? to Guid.

Currently, I get around this by using two generic types, one for Id and another for ParentId, or simply make ParentId Guid instead of Guid?.

Is this the right approach and is there a better way of doing this?

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

0

I don't know if it suits your purpose, but it compiles with this:

public interface ISelfReferenceable<TId> where TId : struct
{
     TId Id {get;set;}
     TId? ParentId {get;set;}
}

Remember that Guid is a value type.

over 4 years ago · Santiago Trujillo Relatório

0

The problem is that TId? is interpreted as a nullable reference type (in fact this is more complicated and depends on the language version and whether you are in a nullable context. See also the explanation under default constraint). You can fix it by adding a where TId : struct generic type constraint to the interface. But of course this limits the applicable types to value types. A string Id would not be possible.

The error also goes away if you declare

public class MyClass : ISelfReferenceable<string>
{
    public string Id { get; set; }
    public string? ParentId { get; set; }
}
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