C
C#3mo ago
AlisterKB

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?
10 Replies
Thinker
Thinker3mo ago
You have to use source.Lastupdated.Value
greyfox
greyfox3mo ago
It's a different type. Just use
Lastupdated = source.Lastupdated.HasValue ? source.Lastupdated.Value : DateTime.Now.ToUniversalTime();
Lastupdated = source.Lastupdated.HasValue ? source.Lastupdated.Value : DateTime.Now.ToUniversalTime();
Thinker
Thinker3mo ago
Alternatively you could rewrite it as Lastupdated = source.Lastupdated is {} lastUpdated ? lastUpdated : DateTime.Now.ToUniversalTime() or just... source.Lastupdated ?? DateTime.Now.ToUniversalTime()
greyfox
greyfox3mo ago
Yeah, the null coalescing operator is more succinct
AlisterKB
AlisterKBOP3mo ago
thank you legends!
Sehra
Sehra3mo ago
DateTime.UtcNow
Thinker
Thinker3mo ago
even better, don't use DateTime :when:
AlisterKB
AlisterKBOP3mo ago
what do I use then ? 🙂
Thinker
Thinker3mo ago
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
AlisterKB
AlisterKBOP3mo ago
I see! reading about it and checking the link. thanks a lot for opening my eyes to better practices, really appreciate it!

Did you find this page helpful?