I would like to add a static method to the DateTime
struct that returns the number of days in a year.
In this answer to a similar but much older question, the answerer writes:
"You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods."
And proceeds to define an extension method to suit the asker's needs.
However, this was in 2009 so I'm wondering if things have changed. From the implementation of DateTime in .NET Core, it seems like DateTime
it is in fact a partial struct
.
I tried to implement my method like this:
namespace MyApplication.MyNamespace
{
public readonly partial struct DateTime
{
public static int DaysInYear(int year)
=> IsLeapYear(year) ? 366 : 365;
}
}
But this doesn't seem to work. Changing the code to use DateTime.IsLeapYear(year)
does not compile either. Changing the file's namespace to System
corrupts all System.DateTime
instances in the rest of my code.
Is there a way to extend the DateTime
struct so I can call e.g. DateTime.DaysInYear(2021)
in my code?
PLEASE NOTE THAT I'M NOT ASKING TO CREATE AN EXTENSION METHOD ON JUST ANY DateTime
OBJECT, I WOULD LIKE IT TO BE AN EXPLICIT STATIC METHOD ON THE DateTime
STRUCT