Search code examples
c#enumsplaying-cards

Is there any benefit in not enum cards c#


I'm going to create a card class in C# for a poker game. All needed actions with cards are going to be implemented in other classes like deck or hand or combination. What type of fields should I use for rank and suit, string or enum or int? Is there any advantage to not using enums?


Solution

  • I would go with enum for both rank and suit.

    Why?

    • Readability of code. While creating new instance of class you can create it like this:

      var card = new Card{ Rank = Rank.King, Suit = Suit.Hearts}

    • Less error-prone - if suit was an int, you could put any number between int.MaxValue and int.MinValue, but only some of values are going to have a meaning. Just try to find the little bug if you wrote 11 instead of 10 somewhere in code, and all of sudden your deck has five kings.

    • Do not be afraid of memory usage - enum is just a nice-looking int, as mentioned in answer by Anders Forsgren. And you can make it a byte, if you need only 8 values, which will take a memory of, well, around one byte. Which considering you are using C# is negligible. Enum can be any of byte, sbyte, short, ushort, int, uint, long, or ulong.

    So, keep it enum and have better-looking, less error-prone, faster code.