using System; // for DateTime
public static bool IsLeapYear(int year) => (new DateTime(year, 2, 28)).AddDays(1.0).Day == 29;
This approach may be considered a "cheat" for this exercise. By adding a day to February 28th for the year, you can see if the new day is the 29th or the 1st. If it is the 29th, then the year is a leap year. This is done by using the AddDays method and the Day property of the DateTime struct.
Shortening
When the body of a function is a single expression, the function can be implemented as an expression-bodied member, like so
public static bool IsLeapYear(int year) =>
(new DateTime(year, 2, 28)).AddDays(1.0).Day == 29;
or
public static bool IsLeapYear(int year) => (new DateTime(year, 2, 28)).AddDays(1.0).Day == 29;
11th Dec 2024
·
Found it useful?