Karthik
Karthik

Reputation: 122

How do I set an enum value inside another enum?

I want something like this.

public enum AgeGroup  
{  
    Teenager = new enum { FromAge = 16, ToAge = 17 },  
    young = new enum { FromAge = 18, ToAge = 24  }   
}

By this I want access it like AgeGroup.Teenager.FromDate.

Upvotes: 1

Views: 1009

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16059

An alternative approach is to create a static class:

public static class AgeGroup
{
   public static class TeenAge
   {
      public static readonly int FromAge = 16;
      public static readonly int ToAge = 17;
   }

  public static class YoungAge
   {
      public static readonly int FromAge = 18;
      public static readonly int ToAge = 21;
   }
}

Now you can refer to the variable, as below:

int teenAgeStarting = AgeGroup.TeenAge.FromAge  //16
int youngAgeStarting = AgeGroup.YoungAge.FromAge  //18

Implementation: DotNetFiddler

Upvotes: 0

Ashish Sapkale
Ashish Sapkale

Reputation: 550

A nested enum is not possible.

You can change your parent enum to a class, and it will work:

public class AgeGroup
{
    public enum Teegaer
    {
        FromAge = 16, ToAge = 17
    }

    public enum young
    {
        FromAge = 18, ToAge = 24
    }
}

Upvotes: 6

Related Questions