Home > front end >  How do I use enums without repeating the enum name again and again?
How do I use enums without repeating the enum name again and again?

Time:10-06

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?

CodePudding user response:

Won't say it's a good idea, but you can do that with using static directive (C# 6.0 I think):

using static ConsoleApp4.PokerCard;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args) {
            PokerHand hand = new(HeartAce, HeartKing);
        }
    }

    public enum PokerCard {
        HeartAce,
        HeartKing
    }

    public class PokerHand {
        public PokerHand(PokerCard a, PokerCard b) {

        }
    }
}

using static <enum> allows to refer to enum members without specifying enum type.

CodePudding user response:

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.

public enum Suit
{
    Clubs, Diamonds, Hearts, Spades
}

public struct Card
{
    public Suit Suit { get; }
    public int Value { get; }
    
    public Card(Suit suit, int value)
    {
        // Aces are high
        if (value < 1 || value > 14)
            throw new ArgumentOutOfRangeException(nameof(value), "Must be between 1 and 14");
        
        Suit = suit;
        Value = value;
    }
}

This lets you create a card using e.g:

var card = new Card(Suit.Spades, 3);

That's still a bit wordy, so we can create some helper methods:

public struct Card
{
    // ...

    public static Card Club(int value) => new Card(Suit.Clubs, value);
    public static Card Diamond(int value) => new Card(Suit.Diamonds, value);
    public static Card Heart(int value) => new Card(Suit.Hearts, value);
    public static Card Spade(int value) => new Card(Suit.Spades, value);
}

This lets us write:

var card = Card.Club(3);

If we then do:

using static Card;

We can write:

var card = Club(3);

See it on SharpLab.

CodePudding user response:

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.

using PC = PokerCard;

PokerHand hand = new(PC.HeartAce, PC.HeartKing, PC.HeartQueen,
                     PC.HeartJack, PC.HeartTen);
  • Related