C# vs Java Enums for C# Beginners
As a seasoned Java developer, transitioning to C# may require some adjustments, including understanding the differences in enums. Let's delve into the disparities between C# and Java enums and how to adapt.
In Java, enums allow for custom methods and fields. C#, on the other hand, offers a simpler enum implementation. However, C# introduces extension methods as a solution to overcome this limitation.
Extension methods enable you to add functionality to existing types without modifying them. For instance, you can create extension methods for your Planet enum to mimic Java's surfaceGravity() and surfaceWeight() methods.
Custom attributes provide another approach for extending enums. You can add a PlanetAttr attribute to define mass and radius properties for each planet, allowing you to access those values in your extension methods.
Here's a C# implementation of the famous Planet enum example, utilizing extension methods and custom attributes:
<code class="c#">using System; using System.Reflection; class PlanetAttr: Attribute { internal PlanetAttr(double mass, double radius) { this.Mass = mass; this.Radius = radius; } public double Mass { get; private set; } public double Radius { get; private set; } } public static class Planets { public static double GetSurfaceGravity(this Planet p) { PlanetAttr attr = GetAttr(p); return G * attr.Mass / (attr.Radius * attr.Radius); } public static double GetSurfaceWeight(this Planet p, double otherMass) { return otherMass * p.GetSurfaceGravity(); } public const double G = 6.67300E-11; private static PlanetAttr GetAttr(Planet p) { return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr)); } private static MemberInfo ForValue(Planet p) { return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p)); } } public enum Planet { [PlanetAttr(3.303e+23, 2.4397e6)] MERCURY, [PlanetAttr(4.869e+24, 6.0518e6)] VENUS, [PlanetAttr(5.976e+24, 6.37814e6)] EARTH, [PlanetAttr(6.421e+23, 3.3972e6)] MARS, [PlanetAttr(1.9e+27, 7.1492e7)] JUPITER, [PlanetAttr(5.688e+26, 6.0268e7)] SATURN, [PlanetAttr(8.686e+25, 2.5559e7)] URANUS, [PlanetAttr(1.024e+26, 2.4746e7)] NEPTUNE, [PlanetAttr(1.27e+22, 1.137e6)] PLUTO }</code>
This implementation allows you to access planet attributes and calculate surface gravity and weight as in the Java example. By understanding these differences and embracing C#'s powerful features like extension methods and custom attributes, transitioning from Java to C# becomes a smooth and efficient process.
The above is the detailed content of How do C# enums compare to Java enums for a Java developer transitioning to C#?. For more information, please follow other related articles on the PHP Chinese website!