Reputation: 2491
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;
}
}
I am able to call the method by passing in both a DateTime? and a DateTime. So how does the compiler understand the difference?
Does that mean if I pass in a DateTime Value, the if statement will essentially be soemthing like
if (true && true)
and all the *.value has been changed to the proper objects? So all endDate.Value are all now EndDates?
Does the compiler cast all parameters that are not Nullables into Nullables during runtime?
Upvotes: 5
Views: 127
Reputation: 66439
Everything in your method remains the same, and the startDate
and endDate
parameters are still instances of the Nullable<T>
struct.
When you pass a "normal" DateTime
to the method, you're taking advantage of the implicit conversion specified in the Nullable<T>
struct:
public static implicit operator Nullable<T>(T value) {
return new Nullable<T>(value);
}
From the MSDN page linked above:
If the value parameter is not null, the Value property of the new Nullable value is initialized to the value parameter and the HasValue property is initialized to true.
Upvotes: 10