CSharp examples for Custom Type:class
Card class represents a playing card.
using System;// w w w . jav a 2 s .c o m class Card { private string Face { get; } // Card's face ("Ace", "Deuce", ...) private string Suit { get; } // Card's suit ("Hearts", "Diamonds", ...) public Card(string face, string suit) { Face = face; // initialize face of card Suit = suit; // initialize suit of card } public override string ToString() => $"{Face} of {Suit}"; } class DeckOfCards { private static Random randomNumbers = new Random(); private const int NumberOfCards = 52; // number of cards in a deck private Card[] deck = new Card[NumberOfCards]; private int currentCard = 0; // index of next Card to be dealt (0-51) public DeckOfCards() { string[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; string[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" }; // populate deck with Card objects for (var count = 0; count < deck.Length; ++count) { deck[count] = new Card(faces[count % 13], suits[count / 13]); } } // shuffle deck of Cards with one-pass algorithm public void Shuffle() { // after shuffling, dealing should start at deck[0] again currentCard = 0; // reinitialize currentCard // for each Card, pick another random Card and swap them for (var first = 0; first < deck.Length; ++first) { // select a random number between 0 and 51 var second = randomNumbers.Next(NumberOfCards); // swap current Card with randomly selected Card Card temp = deck[first]; deck[first] = deck[second]; deck[second] = temp; } } public Card DealCard() { // determine whether Cards remain to be dealt if (currentCard < deck.Length) { return deck[currentCard++]; // return current Card in array } else { return null; // indicate that all Cards were dealt } } } class MainClass { static void Main(){ var myDeckOfCards = new DeckOfCards(); myDeckOfCards.Shuffle(); // place Cards in random order for (var i = 0; i < 52; ++i) { Console.Write($"{myDeckOfCards.DealCard(),-19}"); if ((i + 1) % 4 == 0) { Console.WriteLine(); } } } }