-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Description
It would be very useful if C# enums act like classes, so we can add methods within the enum's block scope:
Java:
enum DaysOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
public boolean isWeekDay(){
return !isWeekEnd();
}
public boolean isWeekEnd(){
return (this == SUNDAY || this == SATURDAY);
}
}
public class Test {
public static void main(String[] args) throws Exception {
DaysOfWeek sun = DaysOfWeek.SUNDAY;
System.out.println("Is " + sun + " a weekend? " + sun.isWeekEnd());
System.out.println("Is " + sun + " a week day? " + sun.isWeekDay());
}
}C#:
public enum DaysOfWeek {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
public static class DaysOfWeekExtensions {
public static bool isWeekDay(this DaysOfWeek day) {
return !day.isWeekEnd();
}
public static bool isWeekEnd(this DaysOfWeek day) {
return (day == DaysOfWeek.SUNDAY || day == DaysOfWeek.SATURDAY);
}
}
public class Test {
public static void Main(String[] args) {
DaysOfWeek sun = DaysOfWeek.SUNDAY;
Console.WriteLine("Is " + sun + " a weekend? " + sun.isWeekEnd());
Console.WriteLine("Is " + sun + " a week day? " + sun.isWeekDay());
/* Example of how C# enums are not type safe */
sun = (DaysOfWeek) 1999;
Console.WriteLine(sun);
}
}Reference: http://www.25hoursaday.com/CsharpVsJava.html#enums (I modified the C# example with extensions)
Reactions are currently unavailable