1

Here's what I'd like to do in CSharp but I dont know how to do this (I know this is not valid C#):

const enum GameOver { Winner, Looser, Tied, };
GameOvers = [
    GameOver.Winner: "Person is the winner",
    GameOver.Looser: "Person is the looser",
    GameOver.Tied: "Game is tied",
]

And later on, I want to be able to call it like:

Display(GameOvers[GameOver.Winner])

(I want to handle a const array of errors like this actually).

How would you do in C#?

Olivier Pons
  • 13,972
  • 24
  • 98
  • 190
  • You could use the Description attribute or [something like this](https://stackoverflow.com/q/424366/1070452) ? – Ňɏssa Pøngjǣrdenlarp Nov 26 '17 at 00:37
  • https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer – Hans Passant Nov 26 '17 at 00:53
  • This question could have what you need: https://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings –  Nov 26 '17 at 02:13

2 Answers2

1

The closest approach that comes into my mind is using a Dictionary<GameOver, string>:

enum GameOver { Winner, Loser, Tied };

Dictionary<GameOver, string> GameOvers =  new Dictionary<GameOver, string>()
{
    {GameOver.Winner, "Person is the winner"}, 
    {GameOver.Loser,  "Person is the loser"},
    {GameOver.Tied,   "Game is tied"}
};

But notice, that you can't make the Dictionary really constant, since the instance is mutable.

adjan
  • 12,203
  • 2
  • 25
  • 45
-1
public static readonly String[] Messages =
{
    "Person is the winner",
    "Person is the looser",
    "Game is tied"
};

public enum GameOver
{
    Winner = 0,
    Looser = 1,
    Tied = 2
}

Display(Messages[(Int32)GameOver.Winner]);

Maybe less compact, but functional. Your strings will also be insured to be immutable thanks to the readonly attribute (What are the benefits to marking a field as `readonly` in C#?).

Tommaso Belluzzo
  • 21,428
  • 7
  • 63
  • 89
  • Strings are always immutable. The array, however, is not. The readonly keyword only makes the variable ``Messages`` read-only, not the array it points to. – dumetrulo Nov 27 '17 at 08:54
  • I problably explained it in a wrong way but the concept behind the code looks kinda clear. – Tommaso Belluzzo Nov 27 '17 at 09:23