2

In java I have :

public enum MyEnum{

    Value1,
    Value2,
    Value3,
  //so on
    }

And a class which will have a property :

public abstract class MyClass{
public EnumSet<MyEnum> myEnum= EnumSet.noneOf(MyEnum.class); }

But also there is an Level interface which groups MyEnum on levels:

public interface Level{


public EnumSet<MyEnum> LEVEL0 = EnumSet.of(Value1,
                                                Value2,
                                                //etc;}
  public EnumSet<MyEnum> LEVEL1 = EnumSet.of(Value3,
                                                    Value4,
                                                    //etc;}

Also there are used the functions used on the myEnum like clone(),addAll(). How should I treat this cases from the C# perspective?

David
  • 127
  • 2
  • 9
  • 1
    You may want to have a look at http://stackoverflow.com/questions/469287/c-sharp-vs-java-enum-for-those-new-to-c – Alex Apr 30 '15 at 23:22

2 Answers2

2

I would suggest using the [Flags] attribute as explained in the microsoft docs

[Flags]
public enum MyEnum
{
    None = 0,
    Value1 = 1 << 0,
    Value2 = 1 << 1,
    Value3 = 1 << 2,
    Value4 = 1 << 3,
    //so on
}

public abstract class MyClass
{
    public MyEnum myEnum = MyEnum.None;

    public void testing()
    {
        // Initialize with two flags using bitwise OR.
        MyEnum workingFlags = MyEnum.Value1 | MyEnum.Value3;

        // Set an additional flag using bitwise OR.
        workingFlags= workingFlags| MyEnum.Value4;
        // workingFlags: Value1, Value3, Value4

        // Remove a flag using bitwise XOR.
        workingFlags = workingFlags ^ MyEnum.Value3;
        // workingFlags: Value1, Value4

        // Test value of flags using bitwise AND.
        bool test = (workingFlags & MyEnum.Value3) == MyEnum.Value3;
        // test = true;
    }
}

public abstract class Level
{
    public MyEnum LEVEL0 = MyEnum.Value1 | MyEnum.Value2;
    public MyEnum LEVEL1 = MyEnum.Value3 | MyEnum.Value4;
}

C# interfaces cannot have properties with values in it. In java it can but it shouldn't, and they really are constants. See this this answer for more info.

1

C# enums are constants, Java enums are classes. To achieve functionality similar to Java you may:

  1. create full blown c# class and/or:
  2. use bit-wise logic and/or:
  3. use Reflection and/or
  4. Enum.GetValues(typeof(...))
Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20