Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending an enum via inheritance

Tags:

java

c#

.net

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.

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)?

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

like image 857
alastairs Avatar asked Sep 10 '08 21:09

alastairs


1 Answers

The reason you can't extend Enums is because it would lead to problems with polymorphism.

Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum.

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?

To eliminate this problem, extending enums is illegal

like image 161
Rik Avatar answered Sep 27 '22 20:09

Rik