Reputation: 15778
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#
?
Upvotes: 1
Views: 1985
Reputation: 23675
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#?).
Upvotes: 0
Reputation: 13652
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.
Upvotes: 1