Enums is a very common concept. It exists, of course, in Java and C# as well. However, Java and C# enums do not have the same capabilities. This blog post aims to show their differences.
In Java, enums are very much like regular classes: they can implement interfaces and have methods. However, they cannot inherit other classes or be explicitly instantiated. They can be viewed as
final classes (or
sealed classes in C#) that already inherit the virtual “enum” class, have only private constructor(s) and a set of pre-defined instances (the values of the enum).
For instance, let’s take the example of the HTTP status codes. In Java, it is possible to write this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
1 2 3 4
In C#, enums are just integers in disguise. The previous snippet can be simulated in C# only because the
code attribute happens to be an
int. Otherwise, it would be very complex to have the same behaviour:
1 2 3 4 5 6
1 2 3 4
To sum up, Java enums are much more powerful than their C# counterparts. I often use these features when I write Java code and I think I would miss them if I had to write C# code on a daily basis.