Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Two level enum

Tags:

c#

.net

oop

enums

Sorry if the question's title is confusing,but i don't know how to ask it. what is really want is to have read-only data that will never change.

currently i have two enums MeterType and SubMeterType

public enum MeterType
{
  Water = 1001,
  Electricity = 1004,
  Gas = 1007
}

and

public enum SubMeterType
{
  DrinkingWater = 1002,
  UsageWater = 1003,
  SubsidiseGas = 1008,
  NonSusbsidisedGas = 1009
} 

Now i would like to use these as follows

To get the MeterType

string meterType = MeterType.Water.ToString("d");

and to get the SubMeterType, is it possible to have something like

string subMeterType = MeterType.Water.DrinkingWater("d");

Shall go for another approach using classes with readonly properties ? or modify these enums to suit my requirement.

like image 930
Mourya Avatar asked Sep 20 '13 07:09

Mourya


People also ask

Can an enum be a double?

Enums type can be an integer (float, int, byte, double etc.) but if you use beside int, it has to be cast. Enum is used to create numeric constants in . NET framework.

Can we assign multiple values to enum?

6. Attaching Multiple Values. The Enum constructor can accept multiple values. Similarly, we can add any values we want to the enum, such as the proper case symbols, “He”, “Li” and “Be”, for example.

Can we create enum inside enum?

We can an enumeration inside a class. But, we cannot define an enum inside a method.


1 Answers

Instead of using enums you might use constant integers in nested classes:

public static class MeterType
{
    public const int Water = 1001;
    public const int Electricity = 1004;
    public const int Gas = 1007;

    public static class Waters
    {
        public const int DrinkingWater = 1002;
        public const int UsageWater = 1003;
    }

    public static class Gases
    {
        public const int SubsidiseGas = 1008;
        public const int NonSusbsidisedGas = 1009;
    }
}
like image 141
Herdo Avatar answered Sep 19 '22 18:09

Herdo