<p>I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java?  I mean "extend" in both the sense of adding new values to an enum, but also in the OO sense of inheriting from an existing enum.  </p>

<p>I assume it's not possible in Java, as it only got them fairly recently (Java 5?).  C# seems more forgiving of people that want to do crazy things, though, so I thought it might be possible some way.  Presumably it could be hacked up via reflection (not that you'd every actually use that method)?</p>

<p>I'm not necessarily interested in implementing any given method, it just provoked my curiosity when it occurred to me :-)</p>

[{'answer_id': 55380, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 0, 'selected': False, 'text': '<p>You can\'t inherit from/extend an enum, you can use <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute.aspx" rel="nofollow noreferrer">attributes</a> to <a href="http://blog.waynehartman.com/articles/84.aspx" rel="nofollow noreferrer">declare a description</a>.  If you\'re looking for an integer value, that\'s built-in.</p>\n'}, {'answer_id': 55381, 'author': 'Chris Roberts', 'author_id': 475, 'author_profile': 'https://Stackoverflow.com/users/475', 'pm_score': 0, 'selected': False, 'text': "<p>Hmmm - as far as I know, this can't be done - enumerations are written at design-time and are used as a convenience to the programmer.</p>\n\n<p>I'm pretty sure that when the code is compiled, the equivalent values will be substituted for the names in your enumeration, thereby removing the concept of an enumeration and (therefore) the ability to extend it.</p>\n"}, {'answer_id': 55383, 'author': 'Oskar', 'author_id': 5472, 'author_profile': 'https://Stackoverflow.com/users/5472', 'pm_score': 2, 'selected': False, 'text': '<p>Adding enums is a fairly common thing to do if you go back to the source code and edit, any other way (inheritance or reflection, if either is possible) is likely to come back and hit you when you get an upgrade of the library and they have introduced the same enum name <em>or</em> the same enum value - I have seen plenty of lowlevel code where the integer number matches to the binary encoding, where you would run into problems</p>\n\n<p>Ideally code referencing enums should be written as equals only (or switches), and try to be future proof by not expecting the enum set to be const</p>\n'}, {'answer_id': 55390, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 2, 'selected': False, 'text': '<p>You can use .NET reflection to retrieve the labels and values from an existing enum at run-time (<code>Enum.GetNames()</code> and <code>Enum.GetValues()</code> are the two specific methods you would use) and then use code injection to create a new one with those elements plus some new ones. This seems somewhat analagous to "inheriting from an existing enum".</p>\n'}, {'answer_id': 55435, 'author': 'Rik', 'author_id': 5409, 'author_profile': 'https://Stackoverflow.com/users/5409', 'pm_score': 8, 'selected': True, 'text': "<p>The reason you can't extend Enums is because it would lead to problems with polymorphism.</p>\n\n<p>Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum.</p>\n\n<p>Suppose a method expects a myEnum value somewhere, for instance as a parameter. It should be legal to supply a MyExtEnum value, because it's a subtype, but now what are you going to do when it turns out the value is D?</p>\n\n<p>To eliminate this problem, extending enums is illegal</p>\n"}, {'answer_id': 55486, 'author': 'tsimon', 'author_id': 1685, 'author_profile': 'https://Stackoverflow.com/users/1685', 'pm_score': 6, 'selected': False, 'text': '<p>When built-in enums aren\'t enough, you can do it the old fashion way and craft your own. For example, if you wanted to add an additional property, for example, a description field, you could do it as follows:</p>\n\n<pre><code>public class Action {\n    public string Name {get; private set;}\n    public string Description {get; private set;}\n\n    private Action(string name, string description) {\n        Name = name;\n        Description = description;\n    }\n\n    public static Action DoIt = new Action("Do it", "This does things");\n    public static Action StopIt = new Action("Stop It", "This stops things");\n}\n</code></pre>\n\n<p>You can then treat it like an enum like so:</p>\n\n<pre><code>public void ProcessAction(Action a) {\n    Console.WriteLine("Performing action: " + a.Name)\n    if (a == Action.DoIt) {\n       // ... and so on\n    }\n}\n</code></pre>\n\n<p>The trick is to make sure that the constructor is private (or protected if you want to inherit), and that your instances are static.</p>\n'}, {'answer_id': 55521, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 2, 'selected': False, 'text': '<p>If you mean extends in the Base class sense, then in Java... no.</p>\n\n<p>But you can extend an enum value to have properties and methods if that\'s what you mean.</p>\n\n<p>For example, the following uses a Bracket enum:</p>\n\n<pre><code>class Person {\n    enum Bracket {\n        Low(0, 12000),\n        Middle(12000, 60000),\n        Upper(60000, 100000);\n\n        private final int low;\n        private final int high;\n        Brackets(int low, int high) {\n            this.low = low;\n            this.high = high;\n        }\n\n        public int getLow() {\n            return low;\n        }\n\n        public int getHigh() {\n            return high;\n        }\n\n        public boolean isWithin(int value) {\n           return value &gt;= low &amp;&amp; value &lt;= high;\n        }\n\n        public String toString() {\n            return "Bracket " + low + " to " + high;\n        }\n    }\n\n    private Bracket bracket;\n    private String name;\n\n    public Person(String name, Bracket bracket) {\n        this.bracket = bracket;\n        this.name = name;\n    }\n\n    public String toString() {\n        return name + " in " + bracket;\n    }        \n}\n</code></pre>\n'}, {'answer_id': 56413, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 4, 'selected': False, 'text': '<p>Enums are supposed to represent the enumeration of all possible values, so extending rather does go against the idea.</p>\n\n<p>However, what you can do in Java (and presumably C++0x) is have an interface instead of a enum class. Then put you standard values in an enum that implements the feature. Obviously you don\'t get to use java.util.EnumSet and the like. This is the approach taken in "more NIO features", which should be in JDK7.</p>\n\n<pre><code>public interface Result {\n    String name();\n    String toString();\n}\npublic enum StandardResults implements Result {\n    TRUE, FALSE\n}\n\n\npublic enum WTFResults implements Result {\n    FILE_NOT_FOUND\n}\n</code></pre>\n'}, {'answer_id': 57405, 'author': 'jwiklund', 'author_id': 4208, 'author_profile': 'https://Stackoverflow.com/users/4208', 'pm_score': 1, 'selected': False, 'text': '<p>Saw a post regarding this for Java a while back, check out <a href="http://www.javaspecialists.eu/archive/Issue161.html" rel="nofollow noreferrer">http://www.javaspecialists.eu/archive/Issue161.html</a> .</p>\n'}, {'answer_id': 1688974, 'author': 'Ken', 'author_id': 205066, 'author_profile': 'https://Stackoverflow.com/users/205066', 'pm_score': 5, 'selected': False, 'text': '<p>You\'re going the wrong way: a subclass of an enum would have <em>fewer</em> entries.</p>\n\n<p>In pseudocode, think:</p>\n\n<pre><code>enum Animal { Mosquito, Dog, Cat };\nenum Mammal : Animal { Dog, Cat };  // (not valid C#)\n</code></pre>\n\n<p>Any method that can accept an Animal should be able to accept a Mammal, but not the other way around.  Subclassing is for making something more specific, not more general.  That\'s why "object" is the root of the class hierarchy.  Likewise, if enums were inheritable, then a hypothetical root of the enum hierarchy would have every possible symbol.</p>\n\n<p>But no, C#/Java don\'t allow sub-enums, AFAICT, though it would be really useful at times.  It\'s probably because they chose to implement Enums as ints (like C) instead of interned symbols (like Lisp).  (Above, what does (Animal)1 represent, and what does (Mammal)1 represent, and are they the same value?)</p>\n\n<p>You could write your own enum-like class (with a different name) that provided this, though.  With C# attributes it might even look kind of nice.</p>\n'}, {'answer_id': 1891211, 'author': 'Darrell Denlinger', 'author_id': 229994, 'author_profile': 'https://Stackoverflow.com/users/229994', 'pm_score': 2, 'selected': False, 'text': "<p>I didn't see anyone else mention this but the ordinal value of an enum is important.  For example, with grails when you save an enum to the database it uses the ordinal value.  If you could somehow extend an enum, what would be the ordinal values of your extensions?  If you extended it in multiple places how could you preserve some kind of order to these ordinals?  Chaos/instability in the ordinal values would be a bad thing which is probably another reason why the language designers have not touched this.  </p>\n\n<p>Another difficulty if you were the language designer, how can you preserve the functionality of the values() method which is supposed to return all of the enum values.  What would you invoke this on and how would it gather up all of the values?</p>\n"}, {'answer_id': 3230740, 'author': 'Magnum', 'author_id': 389712, 'author_profile': 'https://Stackoverflow.com/users/389712', 'pm_score': 1, 'selected': False, 'text': "<p>I would like to be able to add values to C# enumerations which are combinations of existing values.  For example (this is what I want to do):</p>\n\n<p>AnchorStyles is defined as</p>\n\n<p><code>public enum AnchorStyles {\n None = 0,\n Top = 1,\n Bottom = 2,\n Left = 4,\n Right = 8,\n}</code></p>\n\n<p>and I would like to add an AnchorStyles.BottomRight = Right + Bottom so instead of saying</p>\n\n<pre><code>my_ctrl.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;\n</code></pre>\n\n<p>I can just say</p>\n\n<pre><code>my_ctrl.Anchor = AnchorStyles.BottomRight;\n</code></pre>\n\n<p>This doesn't cause any of the problems that have been mentioned above, so it would be nice if it was possible.</p>\n"}, {'answer_id': 18443046, 'author': 'Aniket Thakur', 'author_id': 2396539, 'author_profile': 'https://Stackoverflow.com/users/2396539', 'pm_score': 0, 'selected': False, 'text': '<p>As far as java is concerned it is not allowed because adding elements to an enum would effectively create a super class rather than a sub class.</p>\n\n<p>Consider:</p>\n\n<pre><code> enum Person (JOHN SAM}   \n enum Student extends Person {HARVEY ROSS}\n</code></pre>\n\n<p>A general use case of Polymorphism would be</p>\n\n<pre><code> Person person = Student.ROSS;   //not legal\n</code></pre>\n\n<p>which is clearly wrong.</p>\n'}, {'answer_id': 27519356, 'author': 'Sultan ', 'author_id': 4369010, 'author_profile': 'https://Stackoverflow.com/users/4369010', 'pm_score': 0, 'selected': False, 'text': '<p>Some time back even i wanted to do something like this and found that enum extensions would voilate lot of basic concepts... (Not just polymorphisim)</p>\n\n<p>But still u might need to do if the enum is declared in external library and \nRemember you should make a special caution when using this enum extensions...</p>\n\n<pre><code>public enum MyEnum { A = 1, B = 2, C = 4 }\n\npublic const MyEnum D = (MyEnum)(8);\npublic const MyEnum E = (MyEnum)(16);\n\nfunc1{\n    MyEnum EnumValue = D;\n\n    switch (EnumValue){\n      case D:  break;\n      case E:  break;\n      case MyEnum.A:  break;\n      case MyEnum.B:  break;\n   }\n}\n</code></pre>\n'}, {'answer_id': 58630495, 'author': 'T.Todua', 'author_id': 2377343, 'author_profile': 'https://Stackoverflow.com/users/2377343', 'pm_score': 1, 'selected': False, 'text': '<p><strong>A temporary/local workaround</strong>, when you just want very local/one time usage:</p>\n\n<pre><code>enum Animals { Dog, Cat }\nenum AnimalsExt { Dog = Animals.Dog, Cat= Animals.Cat,  MyOther}\n// BUT CAST THEM when using:\nvar xyz = AnimalsExt.Cat;\nMethodThatNeedsAnimal(   (Animals)xyz   );\n</code></pre>\n\n<p>See all answers at: <a href="https://stackoverflow.com/questions/757684/enum-inheritance">Enum &quot;Inheritance&quot;</a></p>\n'}]
['https://Stackoverflow.com/questions/55375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5296/']