Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an enum to an existing .NET Structure, like Date?

So apparently Microsoft does not have a Months Enum on their Date structure.
What I am wondering is, is it possible to create an enum and attach it to the DateTime structure? Extension Methods come instantly to mind, but I don't know of a way to pull this off using them.

Dim july As DateTime.Months = DateTime.Months.July

Public Enum Months
    January = 1
    February = 2
    March = 3
    April = 4
    May = 5
    June = 6
    July = 7
    August = 8
    September = 9
    October = 10
    November = 11
    December = 12
End Enum

Any one have any thoughts on this?

Update: I am not trying to get the Month name of the current Month or of a given date. I know how to do that. I was just trying to create a class that had a Month property and wanted to use an Enum to represent the month. Since this seems like an item that could have usefulness elsewhere, I hate to put the Enum into my class and would rather have it be "located" in the structure that it is directly related to so that it could be found easily. Thank you for all the responses. I should have been more clear up front as to what I wanted to do.

like image 239
Airn5475 Avatar asked Dec 03 '25 19:12

Airn5475


2 Answers

You can't add properties to an existing type like that.

You can, however add an extension method that will convert from integers to the corresponding Enum value, or simply return the enum value corresponding to the month.

like image 190
Oded Avatar answered Dec 06 '25 09:12

Oded


You could add an extension like this:

public static class DateTimeExtension
{    
    public static Months GetMonth(this Date dt)
    {
        return (Months)dt.Month;
    }
    public static Months GetMonthStr(this Date dt)
    {
        return ((Months)dt.Month).ToString();
    }
}
like image 29
Marco Avatar answered Dec 06 '25 08:12

Marco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!