How does the compiler understand Nullables?

If I have a method:

protected int CalculateActualDuration(DateTime? startDate, DateTime? endDate) { if (startDate.HasValue && endDate.HasValue) { return Math.Abs((int)(endDate.Value.Subtract(startDate.Value).TotalMinutes)); } else { return 0; } } 

Can I call a method by passing as a DateTime? and datetime. So how does the compiler understand the difference?

Does this mean that if I pass in a DateTime value, the if statement will be essentially the same as

 if (true && true) 

and all meaning *. has been changed to the appropriate objects? So all endDate.Value are now EndDates?

Does the compiler provide all parameters that are not Nullables in Nullables at runtime?

+5
source share
1 answer

Everything in your method remains unchanged, and the startDate and endDate are still instances of a Nullable<T> struct .

When you pass a β€œregular” DateTime to the method, you use the implicit conversion specified in the Nullable<T> struct:

 public static implicit operator Nullable<T>(T value) { return new Nullable<T>(value); } 

On the MSDN page linked above:

If the value parameter is not null , the Value property of the new Nullable value is initialized with the value parameter, and the HasValue property is initialized with true .

+10
source

Source: https://habr.com/ru/post/1212923/


All Articles