0

I know this has been answer before, but I cannot seem to find an answer for exactly what I want, the others are too specific. Here is my general question; How do you override an enum? Would this work?

//Enum in the main class it is defined in
public enum GameDifficulty
{
   i1,
   i2,
   i3
}


//Enum class being imported:
using game1.classwithenum;

//Would this override the enum and replace i1, i2, and i3 with f1, f2, and f3?
public enum GameDifficulty
{
   f1,
   f2,
   f3
}
TheQuantumBros
  • 308
  • 3
  • 4
  • 17
  • I don't think you can override enums in C#. In this scenario, I'd just use an int to track GameDifficulty. http://stackoverflow.com/questions/7747539/c-sharp-overriding-enum – Porschiey Jun 01 '13 at 01:10
  • 1
    Side note: I think it is very bad idea and will lead to confusing code that is hard to read and maintain. Note that you can't change other code referring to the same `enum`, so different portions of the code will see different values of something that should be constant. IT is very similar to desire to override value of 2 to be 3. – Alexei Levenkov Jun 01 '13 at 01:11
  • Porschiey's right, you can't but I'm sure there's a better way; perhaps some clever interface/abstract interface. – Russ Clarke Jun 01 '13 at 01:11

2 Answers2

2

The code you pasted won't work as is...

The only way you could do this is by putting each Enumeration inside its own Namespace

But even then, an i1 would not be the same as an f1 as far as type coercion is concerned.

As JW says, you can use the New keyword to override the name, but you'd still have to access it by namespace and a GameDifficulty.i1 would not be equal to a classwithenum.GameDifficulty.i1.

I get a strong feeling that there's a better way to do this, can you clarify what you're trying to achieve, and provide an example maybe ?

Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
  • In XNA Game studio, in the files to help you create a game, there is an Enum called GameDifficulty. It holds three values; Easy, Normal, and Hard. But I want it to hold 4 values named differently, such as Recruit, Soilder, Commander, Veteran. Is this possible? – TheQuantumBros Jun 01 '13 at 01:27
  • Since an enum is basically a list of constants, you can only change them in the source, or create a new one. – tinstaafl Jun 01 '13 at 03:19
1

You can't rename or extend an existing enum, however you can borrow values from it while creating you own enum:

public enum MyGameDifficulty {
  Recruit = GameDifficulty.Easy,
  Soldier = GameDifficulty.Normal,
  Commander = GameDifficulty.Hard,
  Veteran }
HABO
  • 15,314
  • 5
  • 39
  • 57
  • @TheQuantumBros - Don't know of any other. Mantra: _Reflection is the answer, what's the question?_ – HABO Jun 01 '13 at 14:13