Enumeration in Java and C# | Techbirds

Posted on: April 25, 2014 /

Categories: General / Author Name: Swapna Singh

Both languages(Java and C#) define enumerations, but they are implemented in fundamentally different ways. As such, enumerations are one area where tools designed to automatically translate code between the two languages fail.

C# has implemented enumerations in a manner similar to C-programming, that is as wrappers around the bit-flags implemented in value types (integer, bytes, short, etc.). This has performance benefits and improves interaction with C/C++ compiled code, but provides fewer features and can lead to bugs if low-level value types are directly cast to an enumeration type, as is allowed in the C# language. In contrast, Java implements enumerations as full featured collection of classes, requiring more memory and not aiding interaction with C/C++ code, but providing additional features in reflection and intrinsic behavior.

The implementation in each language is described below.

JAVA

Definition :

In Java, the enumeration type is a class, and its values are objects (instances) of that class. The only valid values are the ones listed in the enumeration. The enumeration type may declare fields, allowing each individual enumerated value to reference additional data associated uniquely with that specific value. The enumeration type may also declare or override methods, or implement interfaces.

Combining :

Java enumeration set and map collections provide functionality to combine multiple enumeration values to a combined value. These special collections allows compiler optimization to minimize the overhead incurred by using collections as the combination mechanism.

C#

Definition :

Enumeration in C# are implicitly derived from the Enum type that again is a value type derivative. The value set of a C# enumeration is defined by the underlying type that can be a signed or unsigned integer type of 8, 16, 32 or 64 bits. The enumeration definition defines names for the selected integer values.By default the first name is assigned the value 0 (zero) and the following names are assigned in increments of 1. Any value of the underlying primitive type is a valid value of the enumeration type, though an explicit cast may be needed to assign it.

Combining :

C# supports bit-mapped enumerations where an actual value may be a combination of enumerated values bitwise together. The formatting and parsing methods implicitly defined by the type will attempt to use these values.

614 total views, 1 views today

Share this Onfacebook-4350607twitter-1022085linkedin-2734816google-3156031