Given a base class Coin
public class Coin { }
and two derived classes Coin50Cent and Coin25Cent
public class Coin50 : Coin { }
public class Coin25 : Coin { }
The task is to create an object of a CoinMachine (used for coin exchange, e.g. puting 50 cent coin returns two 25 cent coins) that corresponds the following requierments:
CoinMachinemust have two collections ofCoin25CentandCoin50centobjects.The collections must be derived from an abstract generic class
CoinStack<T>that has two methodsvoid Push(T item); T Pop();CoinMachinemust work as followsCoinMachine.Push(new Coin25()); // puts 25cent in 25c stack CoinMachine.Push(new Coin50()); // puts 50cent in 50c stack CoinMachine.Pop(); // gets 50cent from 50c stack CoinMachine.Pop(); // gets 25cent from 25c stack
Here's my implementation Seems like I have a problem with casting in abstract CoinStack class.
namespace ConsoleApplication1
{
/* Given condition */
class Program
{
static void Main(string[] args)
{
CoinMachine.Push(new Coin25());
CoinMachine.Push(new Coin50());
CoinMachine.Pop<Coin50>();
CoinMachine.Pop<Coin25>();
}
}
public class Coin { }
public class Coin50 : Coin { }
public class Coin25 : Coin { }
/* End given condition */
public interface ICoinStack
{
T Pop<T>();
void Push<T>(T item);
}
/* The problem within this abstract class */
public abstract class CoinStack<T> : ICoinStack
{
private Queue<T> _stack = new Queue<T>();
public T Pop<T>() { return _stack.Dequeue(); }
public void Push<T>(T item) { _stack.Enqueue(item); }
}
public class CoinStack50 : CoinStack<Coin50> { }
public class CoinStack25 : CoinStack<Coin25> { }
public class CoinMachine
{
private static Dictionary<Type, ICoinStack> map;
static CoinMachine()
{
map = new Dictionary<Type, ICoinStack>()
{
{ typeof(Coin50), new CoinStack50() },
{ typeof(Coin25), new CoinStack25() }
};
}
public static T Pop<T>()
{
var type = typeof(T);
return map[type].Pop<T>();
}
public static void Push<T>(T item)
{
var type = typeof(T);
map[type].Push(item);
}
}
}