• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

C# Equivalent to Java Enums

Simple enums in Java have simple equivalents in C#:

Java C#
public enum Simple
{
    FOO,
    BAR
}
public enum Simple
{
    FOO,
    BAR
}

More complex enums in Java unfortunately have exceedingly complex equivalents in C#:

Java C#
public enum Complex
{
    FOO("Foo"),
    BAR("Bar");

    private final String value;

    Complex(String enumValue)
    {
        this.value = enumValue;
    }

    public void InstanceMethod()
    {
        //...
    }
}
using System.Collections.Generic;

public sealed class Complex
{
    public static readonly Complex FOO = new Complex("FOO", InnerEnum.FOO, "Foo");
    public static readonly Complex BAR = new Complex("BAR", InnerEnum.BAR, "Bar");

    private static readonly IList<Complex> valueList = new List<Complex>();

    static Complex()
    {
        valueList.Add(FOO);
        valueList.Add(BAR);
    }

    public enum InnerEnum
    {
        FOO,
        BAR
    }

    public readonly InnerEnum innerEnumValue;
    private readonly string nameValue;
    private readonly int ordinalValue;
    private static int nextOrdinal = 0;

    private readonly string value;

    internal Complex(string name, InnerEnum innerEnum, string enumValue)
    {
        this.value = enumValue;

        nameValue = name;
        ordinalValue = nextOrdinal++;
        innerEnumValue = innerEnum;
    }

    public void InstanceMethod()
    {
        //...
    }

    public static IList<Complex> values()
    {
        return valueList;
    }

    public int ordinal()
    {
        return ordinalValue;
    }

    public override string ToString()
    {
        return nameValue;
    }

    public static Complex valueOf(string name)
    {
        foreach (Complex enumInstance in Complex.valueList)
        {
            if (enumInstance.nameValue == name)
            {
                return enumInstance;
            }
        }
        throw new System.ArgumentException(name);
    }
}


Use Java to C# Converter to convert from Java to C#.     

Additional resource: Java and C# Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.