In my app, article.DatePublished is a nullable DateTime field. Now I have this following code:
list.Add(article.DatePublished.Ticks);
Here I am getting a compile error as Ticks property does not work with nullable DateTimes.
One way of handling this is:
if (article.DatePublished != null)
list.Add(((DateTime)article.DatePublished).Ticks);
This works, but is this an elegant solution? Or can we make it "better"?
Thanks,
Vivek
You need to get at the .Value property of the DateTime?.
if (nullableDate != null) // or if (nullableDate.HasValue)
ticks = nullableDate.Value.Ticks;
You could otherwise use nullableDate.GetValueOrDefault().Ticks, which would normalize a null date into the default value of DateTime, which is DateTime.MinValue.
As Icarus mentioned, I'd use:
if (article.DatePublished != null)
{
list.Add(article.DatePublished.Value.Ticks);
}
Or even:
if (article.DatePublished.HasValue)
{
list.Add(article.DatePublished.Value.Ticks);
}
Depending on what you're trying to do, it could be that LINQ will give you simpler code:
var list = articles.Select(article => article.DatePublished)
.Where(date => date != null)
.Select(date => date.Ticks)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With