0

I'm new to c#, in java we used to have interlinking for enums like below:

 public enum Module
{
    None(SubModule.None),
    Authentication(SubModule.Login),
    User(SubModule.User,SubModule.ForgotPassword,SubModule.ResetPassword)


    private SubModule subModule;

    public Module(SubModule... submodule)
    {

    }

 }

I want to interlink my Modules with submodules, I tried the same in C# its giving compilation error. Is there anyway to do the same in C#.

user1188867
  • 3,726
  • 5
  • 43
  • 69
  • 3
    enums in C# are not classes like they are in Java so I don't think there is a way. – Selman Genç Apr 10 '17 at 01:25
  • @SelmanGenç is right, enums in C# are sort of [syntatic sugar](http://www.dotnetjunkies.net/csharp/enum-working-with-enumerations/)please read the [docs](https://msdn.microsoft.com/en-us/library/sbbt4032.aspx), it might help you.. – Bagus Tesa Apr 10 '17 at 01:38

1 Answers1

1

C# enums are much simpler types than Java enums - they cannot have constructors, methods, or member fields. However, you can achieve similar functionality using a class with static instances that represent each "enumeration."

public sealed class Module
{
    public static Module None { get; } = new Module(SubModule.None);
    public static Module Authentication { get; } = new Module(SubModule.Login);
    public static Module User { get; } = new Module(SubModule.User, SubModule.ForgotPassword, SubModule.ResetPassword);

    private SubModule[] _subModules;
    private Module(params SubModule[] subModules)
    {
        _subModules = subModules;
    }
}

This class allows you to access the static Module instances using basically the same syntax as an enumeration, and the private constructor prevents new instances from being created.

Note that SubModule could be a true C# enum if that suits your needs, or it could also be a class with static properties for "enum" values.

BJ Myers
  • 6,617
  • 6
  • 34
  • 50