Saturday, May 9, 2009

(c#) How can I inherit my enum from another enum?

For example, the enum I want to inherit is:





public enum People


{


Anna,


Mel,


Howard


}





and my enum is:





public enum Lawyer


{


Dan,


Roy,


Diana


}





I want the enum Lawyer to inherit the enum People so that it can access Anna,Mel and Howard. So I somehow want it to look like this:





public enum Lawyer : People


{


Dan,


Roy,


Diana


}





So that Lawter.Anna, Lawyer.Mel and Lawyer.Howard is possible.


Is this possible or is there other ways to do this?

(c#) How can I inherit my enum from another enum?
Hello,





You cannot apply inheritance to an enum since an enum is a type. If you want to do the following ideology, you could create a class with constants, then apply inheritance since it is a class.





--------------


public class People


{


public const int Anna = 0;


public const int Mel = 1;


public const int Howard = 2;


}





public class Lawyer : People


{


public const int Dan = 3;


public const int Roy = 4;


public const int Diana = 5;


}





--------------





This would be immitating the enum structure, and you can allow inheritance. There is no way you can apply inheritance to enum types.





Good Luck





---


Update:





In enums, you can do myenum.ToString() to get back the name of that enum type. The way I showed above cannot do that unless you use reflection. Or use strings to represent each one.





I don't understand why your design is that way? Why can't you have a list of People? Instead of introducing types for each one. Your design seems to be flawed. Would be better to do a List%26lt;People%26gt; and have a People class that contains information about the specific person. Within the People class, you can introduce Properties that describe the person such as, Name, Age, HairColor, whatever you want. So if you already know the people in that application, you can do a InitializePeople() Method that adds a new person to the list then you can do whatever you please...





You can use any other datastructure as well such as Dictionary, Hashtable, etc ..





---


Update 2:





If you want to just access them while coding (the names) then just remove the inherited enums and do them normally. Your design is flawed cause you want to make a list of users as variables. Or just do a class with const string Amy = "Amy"

flower beds

No comments:

Post a Comment