Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested enum in c# and classes

Tags:

c#

enums

class

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

like image 256
Rauf Avatar asked Oct 25 '11 07:10

Rauf


4 Answers

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;
    }
}
like image 133
ojlovecd Avatar answered Oct 17 '22 20:10

ojlovecd


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
like image 41
Frederiek Avatar answered Oct 17 '22 19:10

Frederiek


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

like image 26
Royi Namir Avatar answered Oct 17 '22 18:10

Royi Namir


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
}
like image 28
saintedlama Avatar answered Oct 17 '22 19:10

saintedlama