C#C
C#11mo 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?
Was this page helpful?