Object Oriented Programming using C#

(backadmin) #1

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


The code for the Bank class is given below and this demonstrates how easy it is to use the collection class ‘List’.


class Bank
{
private List<Account> accounts;
public List<Account> Accounts
{
get { return accounts;}
}
public Bank()
{
accounts = new List<Account>();
}
public void AddAccount(Account account)
{
accounts.Add(account);
}
public Account GetAccount(String name,String dob)
{
Account FoundAccount = null;
foreach (Account a in accounts)
{
if ((a.Name == name) && (a.DateOfBirth==dob))
{
FoundAccount = a;
}
}
return FoundAccount;
}
}

Firstly the constructor creates a list of accounts. As with any list this automatically resizes itself, so unlike an array we do
not need to worry about running out of space.


Also when elements are removed the remaining elements are moved so that the blank spaces are deleted. While this is
not hard to do with arrays it is a time consuming process that is handled automatically for us when we use Lists.


Adding an account becomes a trivial task of invoking the Add() method.


Finally retrieving an individual account is fairly simple to do by iterating through the list until the account we are looking
for is found.


Note this list manages a collection of complex objects and when any object is retrieved from the list the methods associated
with that object can be invoked on that object.


This can be demonstrated via the following ‘Main’ method.

Free download pdf