casting required for nullable even after checking for null
would truly appreciate your hep with below 🙏
public class SomeClass
{
public DateTime? Lastupdated { get; set; } public static explicit operator Payment(AddPaymentDTO source) => new Payment() {
Lastupdated = source.Lastupdated is not null? source.Lastupdated : DateTime.Now.ToUniversalTime(), }; } if I write my casting like above I get the error Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?) but if I do like below the its fine with it Lastupdated = source.Lastupdated is not null? (DateTime)source.Lastupdated : DateTime.Now.ToUniversalTime() why is the compiler still bother about it being nullable since I've already checked for it not being null ? is this the right way to go about it ? or is there a better way?
public DateTime? Lastupdated { get; set; } public static explicit operator Payment(AddPaymentDTO source) => new Payment() {
Lastupdated = source.Lastupdated is not null? source.Lastupdated : DateTime.Now.ToUniversalTime(), }; } if I write my casting like above I get the error Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?) but if I do like below the its fine with it Lastupdated = source.Lastupdated is not null? (DateTime)source.Lastupdated : DateTime.Now.ToUniversalTime() why is the compiler still bother about it being nullable since I've already checked for it not being null ? is this the right way to go about it ? or is there a better way?
10 Replies
You have to use
source.Lastupdated.Value
It's a different type.
Just use
Alternatively you could rewrite it as
Lastupdated = source.Lastupdated is {} lastUpdated ? lastUpdated : DateTime.Now.ToUniversalTime()
or just... source.Lastupdated ?? DateTime.Now.ToUniversalTime()
Yeah, the null coalescing operator is more succinct
thank you legends!
DateTime.UtcNow
even better, don't use
DateTime
:when:what do I use then ? 🙂
NodaTime
https://www.nodatime.org/
It's a completely separate alternative to the built-in date API which is a lot more well-structured
buuuuut that's neither here nor there, go ahead with what you're using rn, it's fine
I see! reading about it and checking the link.
thanks a lot for opening my eyes to better practices, really appreciate it!