0

Consider the following C# code:

enum BaseState {STATE_ONE, STATE_TWO}

class Base{ BaseState baseSate;}

enum DervState {STATE_ONE, STATE_TWO, STATE_THREE}

class Derv : Base { DervState dervState;}

Is there any way, I can relate the two enumerations so that DervState picks all states from the base and adds few additional ones.

Thanks in advance.

Yelena
  • 423
  • 3
  • 14

1 Answers1

2

You just can't inherit from an enum, that's it. Wanting to do so is very suspect.

Enums are intended for use cases when you have literally enumerated every possible value a variable could take. Think use cases like days of the week or months of the year or config values of a hardware register. Things that are both highly stable and representable by a simple value.

Enum code smells happen most often when the different enum's correspond to different types with different behaviours but the same interface. For example, talking to different backends, rendering different pages, etc. These are much more naturally implemented using polymorphic classes or other structures.

In short, if you need this sort of facility, look at classes where you can separate your concerns a lot easier and encapsulate functionality or other structures like dictionaries or arrays, or even consts. If you really need enum inheritance, look at two separate enums that describe two different things, there shouldn't be a case to mix them.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141