Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALL or null with enums?

Tags:

c#

null

enums

I've noticed I've been doing this inconsistently within the same project. In some places, I'll have an enum with an ALL option, and in others I'll have my enum as a nullable type with a null value indicating all (or no filter.)

I noticed it when I had to write something like if (Region != null && Region != Regions.ALL).

Is there a reason to go one way or the other?

like image 811
Serinus Avatar asked Jan 11 '12 02:01

Serinus


3 Answers

Using Regions.All is more explicit as far as conveying the meaning goes. You can "assign" that meaning to null, and the computer would be fine with it. The readers of your program, however, would need to decypher that meaning from the way you use the null enum value, or from reading your comments. Regions.All, on the other hand, is self-documenting and self-explanatory.

like image 123
Sergey Kalinichenko Avatar answered Oct 05 '22 06:10

Sergey Kalinichenko


Where Enums that you need to specify either an "All" or "Null" type, I usually go with the Flag attribute and use bitwise & and |. That is a much more flexible solution.

As for making a nullable type or having one option be "All", I think if it makes sense to you, then I see no problem with it. I just prefer using Flags.

like image 40
joe_coolish Avatar answered Oct 05 '22 07:10

joe_coolish


Generally, we use null to mean 'unspecified' or 'non-existent' or 'non-applicable'. So, in the case of a filter, it makes sense to allow for null, because it means 'no filtering'.

In addition, an enum called Regions probably has values like Northeast, Southeast, Midwest, Southwest, and West. Now, please correct me if I am wrong, but I do not think there is any region called "All" in the USA. During my several year long stay over there I heard the weatherman on the TV speaking of the weather in the West, and of the weather in the Southeast, etc. but never of the weather in some place called "All". So, I am inclined to believe that there is no such region. Therefore, including "All" in an enum of regions is a hack. Suddenly, the Regions enum is not about regions; instead it is about regions and/or filtering thereof. Shifts in meaning of this kind are something to be aware of in programming and to generally avoid.

like image 23
Mike Nakis Avatar answered Oct 05 '22 06:10

Mike Nakis