C
C#3w 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
Thinker3w ago
You have to use source.Lastupdated.Value
greyfox
greyfox3w 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
Thinker3w ago
Alternatively you could rewrite it as Lastupdated = source.Lastupdated is {} lastUpdated ? lastUpdated : DateTime.Now.ToUniversalTime() or just... source.Lastupdated ?? DateTime.Now.ToUniversalTime()
greyfox
greyfox3w ago
Yeah, the null coalescing operator is more succinct
AlisterKB
AlisterKBOP3w ago
thank you legends!
Sehra
Sehra3w ago
DateTime.UtcNow
Thinker
Thinker3w ago
even better, don't use DateTime :when:
AlisterKB
AlisterKBOP3w ago
what do I use then ? 🙂
Thinker
Thinker3w 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
AlisterKBOP3w 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?