C#
Java
Enums
Programming
Beginners

C vs Java Enum for those new to C

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Enumerations in C# and Java

Enumerations (enums) are a special kind of data type in both C# and Java that enable developers to define a set of named values that represent integer constants. They enhance readability and reliability by lowering errors associated with specifying constant values directly.

This article will explore the similarities and differences between enums in C# and Java, providing technical explanations and examples relevant for beginners.

Intro to Enums

C#

An enum in C# is a value type that provides a way for developers to define sets of named integral constants across a common type. C# enums are defined using the enum keyword.

Syntax Example

csharp
1enum DaysOfWeek
2{
3    Sunday,
4    Monday,
5    Tuesday,
6    Wednesday,
7    Thursday,
8    Friday,
9    Saturday
10}

Java

In Java, enums are classes that define values consisting of a fixed set of constants offered under the enum keyword in Java 5 and later versions.

Syntax Example

java
1public enum DaysOfWeek {
2    SUNDAY,
3    MONDAY,
4    TUESDAY,
5    WEDNESDAY,
6    THURSDAY,
7    FRIDAY,
8    SATURDAY
9}

Key Differences

Initialization Values

  • C#: By default, the first enumerated value starts at 0 and increments by 1 for subsequent values. You can explicitly set your preferred value for each item.
csharp
1  enum SeverityLevel
2  {
3      Low = 1,
4      Medium = 2,
5      High = 3
6  }
  • Java: Enums do not inherently correspond to integers; they are full-fledged objects. Their ordinal() method returns the zero-based position of the enum constant.

Methods and Behavior

  • C#: Enums cannot contain methods, but they can be enhanced with methods using static classes or extension methods.
  • Java: Enums can contain methods, constructors, and instance variables. This allows modeling each enum constant as an object.
java
1  public enum TrafficLight {
2      RED(30), YELLOW(5), GREEN(60);
3
4      private int duration;
5
6      TrafficLight(int duration) {
7          this.duration = duration;
8      }
9
10      public int getDuration() {
11          return duration;
12      }
13  }

Inheritance

  • C#: Enums implicitly inherit from System.Enum but cannot directly inherit from any other type, nor can they serve as a base class.
  • Java: All enums implicitly extend java.lang.Enum and cannot extend other classes due to Java's single inheritance model.

Usage in Collections

  • C#: Enums can be used in arrays, lists, dictionaries, and other collections easily due to their underlying integer basis.
  • Java: Enums can be used in collections similarly. However, since they're treated as objects, using enums may involve more overhead compared to primitive types.

Comparison Table

FeatureC# EnumJava Enum
Declarationenum Days { Monday, Tuesday }enum Days { MONDAY, TUESDAY }
Default InitializationStarts from 0Orchestrated via ordinal values
InheritanceInherits from System.Enum and cannot extend other classesExtends java.lang.Enum
MethodsCan use static or extension methodsCan define custom methods and constructors
Usability in CollectionsWorks seamlessly due to integral natureUsable in collections but is treated as an object

Additional Details

Conversions

  • C#: Enum values can be easily cast to integers and vice versa.
csharp
  int fridayValue = (int)DaysOfWeek.Friday;  // fridayValue = 5
  DaysOfWeek day = (DaysOfWeek)4;            // day = Thursday
  • Java: The ordinal() method provides the position index, and there isn't direct casting between integers and enums.
java
  int ordinal = DaysOfWeek.THURSDAY.ordinal(); // ordinal = 4

EnumSet and EnumMap in Java

Java provides built-in classes like EnumSet and EnumMap for efficient set operations and mapping of enum types.

java
import java.util.EnumSet;

EnumSet<DaysOfWeek> weekend = EnumSet.of(DaysOfWeek.SATURDAY, DaysOfWeek.SUNDAY);

Flags

  • C#: Enums can be annotated with the [Flags] attribute for better handling of bitwise operations, representing combinations of options.
csharp
  [Flags]
  enum FileAccess { Read = 1, Write = 2, Execute = 4 }

C# and Java enums serve the same purpose but differ significantly in implementation and capabilities. Understanding both can greatly enhance your coding efficiency across different platforms and projects.


Course illustration
Course illustration

All Rights Reserved.