Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!