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

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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