0

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

JansthcirlU
  • 688
  • 5
  • 21
  • You're looking for extensions methods just add a parameter to your method (this DateTime date) – johnny 5 Mar 08 '21 at 18:53
  • `I'm wondering if things have changed` there's no reason to. Using extension methods is far easier than a hypothetical `partial` syntax. Besides, `partial` is already used for something completely different – Panagiotis Kanavos Mar 08 '21 at 18:55
  • @gunr2171 that would make it work on any `DateTime`, I was wondering if I could make it specifically work as a static method like `DateTime.IsLeapYear(int year)` or `DateTime.DaysInMonth(int year, int month)` – JansthcirlU Mar 08 '21 at 18:55
  • 4
    All parts of a "partial" type must be defined in the same assembly, as partial is a language feature not a CLR feature: https://stackoverflow.com/questions/3858649/partial-classes-in-separate-dlls – Klaus Gütter Mar 08 '21 at 18:57
  • @KlausGütter thanks, that actually is a useful link – JansthcirlU Mar 08 '21 at 18:58

0 Answers0