Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda