'How to not get errors accessing DateTime? properties in .NET with continue?

I have a loop that iterates over nullable DateTimes, continues the loop if they are null or uses their Year and Month attributes if not.

This is a simplified example:

public static void Main()
{
    var dateTimes = GetDateTimes();
    
    foreach (var dateTime in dateTimes)
    {
        if (dateTime is null)
            continue;
        
        Console.WriteLine(dateTime.Year.ToString(), dateTime.Month.ToString());
    }
}

public static IEnumerable<DateTime?> GetDateTimes()
{
    return new List<DateTime?> { new DateTime(2021, 03, 22), null, DateTime.Now };
}

However, C# doesn't seem to be able to tell that, after the if-continue, the dateTime item is not null, and doesn't allow me to access its properties.

Even with an if (dateTime != null) it still complains?

Is there a way to make C# acknowledge the correct type, preferably with the if-continue structure?

The project uses .NET Core 3.1.

demo



Solution 1:[1]

Using dateTime.GetValueOrDefault or dateTime.Value solved the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asghwor