C#

C#

By DeepSource

Use DateTime.Compare() to compare DateTimes CS-W1018

Bug risk
Autofix

Invoking the .ToString method and then using the resultant string for comparison is not guaranteed to work everytime as the resultant string may not necessarily be the best representation of an entity. Instead, it is recommended that you use appropriate methods based on the entities' types. In case of DateTime, consider using DateTime.Compare() to compare 2 DateTimes.

Examples

Bad Practice

if (actualDate.ToString() == expectedDate.ToString())
{
    // ...
}

Recommended

if (DateTime.Compare(actualDate, expectedDate) == 0)
{
    // ...
}

Reference