Beginning Visual C# Exercises - Chapter 10
1. public class MyClass
{
protected string myString;
public string ContainedString
{
set
{
myString = value;
}
}
public virtual string GetString()
{
return myString;
}
public MyClass(string theMessage)
{
myString = theMessage;
}
}
... Instantiate and call as follows
MyClass testThis = new MyClass("This is my base class!");
Console.WriteLine(testThis.GetString());
2. public class MyDerivedClass : MyClass
{
public override string GetString()
{
return base.GetString() + " (output from derived class)";
}
public MyDerivedClass(string theMessage) : base(theMessage)
{
}
}
... Instantiate and call as follows
MyDerivedClass testThis = new MyDerivedClass("This is my derived answer!");
Console.WriteLine(testThis.GetString());
3. public class MyCopyableClass
{
public int theNumber;
public object GetCopy()
{
// Make a shallow copy
return MemberwiseClone();
}
}
... Instantiate and compare field value
MyCopyableClass theOriginal = new MyCopyableClass();
theOriginal.theNumber = 33;
MyCopyableClass theDuplicate = (MyCopyableClass)theOriginal.GetCopy();
// field value in both objects should match
if (theOriginal.theNumber == theDuplicate.theNumber)
Console.WriteLine("Test 1: The two field values match each other");
else
Console.WriteLine("Test 1: Oh no! The two field values differ");
theDuplicate.theNumber = 16;
// Field value now should not match
if (theOriginal.theNumber == theDuplicate.theNumber)
Console.WriteLine("Test 2: The two field values match each other");
else
Console.WriteLine("Test 2: Oh no! The two field values differ");
4. ... At top of code
using Ch10CardLib;
... Takes many attempts to obtain a flush!!
int i, j;
const int rawDeal = 5;
string theHand, theSuit;
bool isFlush;
// Get the deck ready to deal
Deck myDeck = new Deck();
myDeck.Shuffle();
// Deal maximum 50 cards @ 5 cards per hand (loop 10 times)
for (i = 0; i < 10; i++)
{
// Initialize the hand before each deal
theHand = "";
// Peek at the suit of first card dealt
theSuit = myDeck.GetCard((i * rawDeal) + 1).suit.ToString();
// Presume this hand will be a flush
isFlush = true;
// Deal five cards and compare suit to first card
for (j = 1; j <= rawDeal; j++)
{
// Look at card dealt
Card tempCard = myDeck.GetCard((i * rawDeal) + j);
// Stow card into your hand
theHand = theHand + tempCard.ToString() + "\n";
// Do you still have a flush?
isFlush = isFlush && tempCard.suit.ToString() == theSuit;
}
// Celebrate if you have a flush!
if (isFlush == true)
{
Console.WriteLine(theHand + "Flush!");
continue;
}
// Tell the world you are an unlucky poker player
if (i == 9 && isFlush == false)
Console.WriteLine("No flush");
}
}
|