5

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?

1
  • The answer to your final question is "yes". Think of a nullable DateTime as a normal DateTime with a Boolean glued to it that indicates its nullity. Now is it clear how the compiler could deal with converting a normal DateTime to a nullable DateTime? Feb 9, 2015 at 3:43

1 Answer 1

10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.