Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler understand Nullables?

Tags:

c#

nullable

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?

like image 436
SamIAm Avatar asked Feb 09 '15 01:02

SamIAm


People also ask

What is nullable compiler?

Nullable reference types are implemented as type annotations that provide semantic rules to the compiler. If the type argument for T is a reference type, T? references the corresponding nullable reference type. For example, if T is a string , then T? is a string? .

How do you define a nullable?

The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.

Why do we use nullable in C#?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

What is the point of nullable string?

Nullable type in C# is used to assign null values to value type variables like to the variables of type int, float, bool, etc., because they cannot store null values. On the other hand, we cannot use nullable with string or any other reference type variable because it can directly store null value.


1 Answers

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.

like image 184
Grant Winney Avatar answered Sep 21 '22 16:09

Grant Winney