Elias Johannes
Elias Johannes

Reputation: 734

Why does .NET's DayOfWeek enum doesn't have a null value?

Refering to this article every enum should have a null value, which totally makes sense. However I wanted to write a function that returns data based on the day of the week but as an optional parameter so you can get the data from all the week days if you don't provide a DayOfWeek value. Something like the following (demonstration code):

private List<Class> GetData(DayOfWeek Day = DayOfWeek.Empty)
{
}

As you can see here the DayOfWeek enum doesn't provide an empty value. Obviously i can work my way around by converting the DayOfWeek to a string or an integer, but basically it feels like this DayOfWeek enum speaks against Microsoft's own design guidelines?

Is there any reason why this enum is like it is or is this just a design flaw?

Upvotes: 1

Views: 625

Answers (1)

mjwills
mjwills

Reputation: 23898

The text in English is clearer:

A non-flags−attributed enumeration should define a member that has the value of zero so that the default value is a valid value of the enumeration.

They key difference is that English is clearer that the requirement is for a value of zero (not null, since enum members can't have a null value).

DayOfWeek meets this requirement, because it has Sunday:

Sunday 0 Indicates Sunday.

The intent here is that if you do code like https://dotnetfiddle.net/H4Eq1k (whereby you declare a variable of the enum type but don't assign anything to it, so it has the default 0 value) then you get meaningful results (i.e. 0 represents a valid value of the enum).

If what you are trying to do is allow some optional notion of DayOfWeek then you likely want a nullable parameter:

private List<Class> GetData(DayOfWeek? Day = null)
{
}

This will allow you to pass a day of the week if you want (with the value of null being used if you don't pass a value).

Upvotes: 8

Related Questions