C#

C#

Made by DeepSource

Detected the use of arithmetic operation to construct a DateTime object CS-W1080

Bug risk
Critical

The DateTime constructor allows you to specify the year, month, day, and time to construct a DateTime object. However, this constructor throws an ArgumentOutOfRangeException exception if the specified date is invalid. The use of addition and subtraction operations can lead to the creation of invalid dates. Instead, it is recommended that you use APIs such as AddDays(), AddMonths(), and AddYears() to construct a DateTime object since these methods handle invalid dates more appropriately.

Bad Practice

var now = DateTime.Now;
// Throws `ArgumentOutOfRangeException` exception if `now` points to Jan 29.
new DateTime(now.Year, now.Month + 1, now.Day + 1, 0, 0, 0, DateTimeKind.Utc);

Recommended

var now  = DateTime.Now;
// Rolls over appropriately without throwing an `Exception`.
var next = now.AddDays(1).AddMonths(1);