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

169
Visualizações
Why do ternary operator and if statement return different results?

In the following example, I'm returning a DateTimeOffset? using the default value

var a = ConvertToDateTimeOffsetA(null); // 1/1/0001 12:00:00 AM +00:00
var b = ConvertToDateTimeOffsetB(null); // null

private static DateTimeOffset? ConvertToDateTimeOffsetA(DateTime? date)
{
    return date != null
        ? new DateTimeOffset(date.Value, TimeSpan.Zero)
        : default;
}
private static DateTimeOffset? ConvertToDateTimeOffsetB(DateTime? date)
{
    if (date != null) 
        return new DateTimeOffset(date.Value, TimeSpan.Zero);
    return default;
}

Why is there a difference between the returned output in the ternary compared to the if statement?

My guess would be the ternary first coerces the type to DateTimeOffset and then inline converts back to Nullable<DateTimeOffset>, but I'm not quite sure why?

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

0

In the ternary version, it is interpreting your default as default(DateTimeOffset), the other output expression type in the conditional. Then it is interpreting the ternary as a whole as a nullable, which will never be null.

In the second case, your return is using default(DateTimeOffset?), from the declared return type.

In this case, you may want to use an explicit type in the default expression, or: just use the second form and add a comment (and ideally a unit test), so nobody "fixes" it in the future.

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