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

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I've done just before you answered ;^) Thanks a lot, and have a nice day ahead!
0
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#?).

2 Comments

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.
I problably explained it in a wrong way but the concept behind the code looks kinda clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.