1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By David Bolton, About.com

9 of 10

A Longer Example - Dealing Playing Cards

This example uses a struct, a class and a static field. Card games are popular on the web and example 8 demonstrates how to setup and use a pack of cards.

Download Example 8

I've chosen a struct for each playing card; there's little in the way of code apart from the overridden ToString() method. This uses a static bool ShortCard to output the cards in either long format E.g. King Spades or short, e.g. KS. This is a public static field in the CardType struct. Being static, it affects every card.

CardType.ShortCard = false; // false = long format
Enums are used for both the card values and suits. The Deck class holds an array of 52 cards and these are created by an initializer. A double loop then initializes the deck of cards. You can verify this by commenting out the ShuffleDeck() call and the cards will be printed in order. Two for loops would have done but this gave a chance to use the foreach construct. This iterates through all members of the CardSuit and CardValue enums.
int index=0;
foreach (CardSuit Suit in Enum.GetValues(typeof(CardSuit)))
  {
   foreach (CardValue Value in Enum.GetValues(typeof(CardValue)))
      {
         cards[index].Value = Value;
         cards[index].Suit = Suit;
         index++;
      }
  }
The first foreach is the same as
for (CardSuit Suit = CardSuit.Hearts;Suit < CardSuit.Spades;Suit++)
But the foreach is all round better- you're not going to pick the wrong value in the For loop as I did. Hearts was the first enum value, but the Intellisense feature of the IDE kept displayed the available values in alphabetical order.

On the next page Using an Indexer

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. A Longer Example - Dealing Playing Cards

©2009 About.com, a part of The New York Times Company.

All rights reserved.