Object Oriented Programming using C#

(backadmin) #1

Object Oriented Programming using C#
Generic Collections and how to Serialize them


There are some significant changes to the Bank class that revolve around the fact that it is a Dictionary not a set that is
being created. The code for the Bank class is shown below :-


class Bank
{
private Dictionary<int,Account> accounts;
public Dictionary<int,Account> Accounts
{
get { return accounts;}
}
public Bank()
{
accounts = new Dictionary<int, Account>();
}
public void AddAccount(int number,Account account)
{
try
{
accounts.Add(number, account);
}
catch (Exception)
{
}
}
public Account GetAccount(int number)
{
Account a;
accounts.TryGetValue(number, out a);
return a;
}
}

In the code above when creating the dictionary you can see that two data types are specified :-. Firstly the type for the
dictionary key is specified – in our case we will use a simple ‘int’ for an account number. Secondly the data type for the
value is specified – in our case the value is a complete account object. Hence the segment of code below :-


private Dictionary<int,Account> accounts;

The dictionary class defines two very useful methods for us, Add() and TryGetValue().


The Add() methods requires two parameters, the ‘Key’ and the ‘Value’. Hence we must provide both the account number
and the account object to be added to the dictionary :-


accounts.Add(number, account);
Free download pdf