I have code like:
PokerHand hand = new(PokerCard.HeartAce, PokerCard.HeartKing, PokerCard.HeartQueen,
PokerCard.HeartJack, PokerCard.HeartTen);
where PokerCard
is defined as:
public enum PokerCard : int
{
SpadeAce = 1, SpadeTwo = 2, SpadeThree = 3, SpadeFour = 4, SpadeFive = 5,...
}
Can I do something like:
with (PokerCard) {
PokerHand hand = new(HeartAce, HeartKing, HeartQueen, HeartJack, HeartTen);
}
in C#/ASP.NET?
3
Answers
Answer: (edited) You can apparently, but I don’t think you should…
If you just want to type fewer characters, you can create an alias.
Won’t say it’s a good idea, but you can do that with using static directive (C# 6.0+ I think):
using static <enum>
allows to refer to enum members without specifying enum type.It’s rare to have every possible card defined in an enum. People normally define a struct which contains both the value and a suit.
This lets you create a card using e.g:
That’s still a bit wordy, so we can create some helper methods:
This lets us write:
If we then do:
We can write:
See it on SharpLab.