Thursday, February 10, 2011

Enumerations

Enums are used to create and group together a list of user defined named constants. Although on the surface the enumerated types in C# and Java seem quite similar there are some significant differences in the implementation of enumerated types in both languages. In Java, enumerated types are a full fledged class which means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe.
The following code sample highlights the differences between enums in both languages.
C# Code
using System;

public enum DaysOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}

public class Test{

public static bool isWeekDay(DaysOfWeek day){
return !isWeekEnd(day);
}

public static bool isWeekEnd(DaysOfWeek day){
return (day == DaysOfWeek.SUNDAY || day == DaysOfWeek.SATURDAY);
}

public static void Main(String[] args){

DaysOfWeek sun = DaysOfWeek.SUNDAY;
Console.WriteLine("Is " + sun + " a weekend? " + isWeekEnd(sun));
Console.WriteLine("Is " + sun + " a week day? " + isWeekDay(sun));

/* Example of how C# enums are not type safe */
sun = (DaysOfWeek) 1999;
Console.WriteLine(sun);

}
}

Java Code
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());
}
}

No comments:

Post a Comment