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

198
Vistas
Why isn't this compiling? Cannot convert from 'X?' to 'X'

I'm facing an unexpected issue (or is this the expected behaviour?). The following code is not compling and it's giving me the error:

CS1503 Argument 1: cannot convert from 'long?' to 'long'

public static void Add(long? ticks)
{
    if (ticks != null)
    {
        new DateTime(ticks);
    }
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

There's no implicit conversion from Nullable<T> to T - you can do it explicitly via a cast, e.g. new DateTime((long) ticks), or use the Value property, e.g. new DateTime(ticks.Value).

As an alternative that I'd generally prefer now, you can use pattern matching from C# 7 to make it slightly simpler, extracting the non-null value in the same step where you check that it is non-null:

public static void Add(long? ticks)
{
    // This will match if ticks is non-null, and assign the value
    // into the newly-introduced variable "actualTicks"
    if (ticks is long actualTicks)
    {
        var dt = new DateTime(actualTicks);
        // Presumably use dt here
    }
}
over 4 years ago · Santiago Trujillo Denunciar

0

You can implicitly widen from long to long?, but you can't implicitly narrow from long? to long.

You need to do this:

public static void Add(long? ticks)
{
    if (ticks != null)
    {
        new DateTime(ticks.Value);  // or (long)ticks
    }
}
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