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);
}
}
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
}
}
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
}
}