8

I heard that nesting of enum is not possible in C#. Then how can convert the following structure to a class hierarchy or something else. So I want the class to act as an enum

enter image description here

3
  • 1
    what have you tried so far ? does it work ? if no, what is it supposed to do ? Commented Oct 25, 2011 at 7:03
  • 1
    Do you mean an enum or an enumerable? The above looks more like something that would be modelled by an enumerable than by an enum. Commented Oct 25, 2011 at 9:02
  • This question it's old, but I made a suggestion (on roslyn github project) to implement this feature in next versions of C# github.com/dotnet/roslyn/issues/13192 Commented Aug 18, 2016 at 15:13

4 Answers 4

4

nested classes and const fields

class Cat1
{
    public const int Public = 1;
    public class Private
    {
        public const int Abc = 2;
        public const int Mno = 3;
        public const int Pqr = 4;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting the variable would just be an int, so could get given an invalid value from somewhere else.
2
public class Cat1
{
  public enum Publicpart
  {
     Xyz
  }

  private enum Privatepart
  {
     Abc, Mno, Pqr
  }
}

then you can call it like this

Cat1.Publicpart.Xyz

or if you have private acces

Cat1.Privatepart.Abc

Comments

1

you can use the hirerchy as class structure , which every class has a property of its own of enum

Comments

1

You should rethink if you want to solve this problems via enums because the first enum category represents to me some kind of "visibility" concept while the second category is only valid of instances with visibility "public".

What about solving your issue with something like this:

public enum Visibility
{
    Public,
    Private
}

public abstract class VisibilityState
{
    public Visibility Visibility { get; private set; }

    protected VisibilityState(Visibility visibility)
    {
        Visibility = visibility;
    }
}

public class PublicVisibilityState : VisibilityState
{
    public PublicVisibilityState() : base(Visibility.Public) { }
}

public class PrivateVisibilityState : VisibilityState
{
    public PrivateVisibilityState() : base(Visibility.Private) { }
    public OtherEnum OtherEnumState { get; set; }
}

public enum OtherEnum
{
    Abc, Mno, Pqr
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.