C# vs Java Enums: A Comparative Guide
If you're transitioning from Java to C#, you may notice some differences in how enums are implemented. While C# enums appear simpler initially, they offer distinct advantages through extension methods and custom attributes.
Key Differences
Example with Extension Methods and Custom Attributes
We can define an enum for planets and add extension methods for GetSurfaceGravity() and GetSurfaceWeight():
public enum Planet { [PlanetAttr(3.303e+23, 2.4397e6)] MERCURY, [PlanetAttr(4.869e+24, 6.0518e6)] VENUS, [PlanetAttr(5.976e+24, 6.37814e6)] EARTH, ... } public static class Planets { public static double GetSurfaceGravity(this Planet p) { PlanetAttr attr = GetAttr(p); ... } ... }
We can then use these extension methods to perform calculations similarly to the Java example:
double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/Planet.EARTH.GetSurfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.GetSurfaceWeight(mass));
This example demonstrates how to create a C# enum with enhanced functionality that closely resembles the Java implementation.
The above is the detailed content of How can C# Enums be Enhanced with Extension Methods and Custom Attributes to Mimic Java Enum Functionality?. For more information, please follow other related articles on the PHP Chinese website!