Year in Nullable DateTime

First check if it has a Value:

if (date.HasValue == true)
{
    //date.Value.Year;
}

Replace DateofDiagnosis.Year with DateofDiagnosis.Value.Year

And check the DateofDiagnosis.HasValue to assert that it is not null first.

I would write the code like this:

private bool TryCalculateAgeAtDiagnosis( DateTime? dateOfDiagnosis, 
                                         DateTime? dateOfBirth, 
                                         out int ageInYears)
{
    if (!dateOfDiagnosis.HasValue || !dateOfBirth.HasValue)
    {
        ageInYears = default;
        return false;
    }

    ageInYears = dateOfDiagnosis.Value.Year - dateOfBirth.Value.Year;

    if (dateOfBirth > dateOfDiagnosis.Value.AddYears(-ageInYears))
    {
        ageInYears--;
    }
    return true;
}

Use nullableDateTime.Value.Year.

Tags:

C#

.Net