15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

102 ❘ ChaPTer 4 inheritAnce<br />

Notice the name of the interface, IBankAccount . It ’ s a convention that an interface name traditionally starts<br />

with the letter I, so that you know it ’ s an interface.<br />

Chapter 2, “ Core <strong>C#</strong>, ” pointed out that, in most cases, .<strong>NET</strong> usage guidelines<br />

discourage the so - called Hungarian notation in which names are preceded by a letter<br />

that indicates the type of object being defi ned. Interfaces are one of the few exceptions<br />

in which Hungarian notation is recommended.<br />

The idea is that you can now write classes that represent bank accounts. These classes don ’ t have to be<br />

related to each other in any way; they can be completely different classes. They will, however, all declare<br />

that they represent bank accounts by the mere fact that they implement the IBankAccount interface.<br />

Let ’ s start off with the fi rst class, a saver account run by the Royal Bank of Venus:<br />

namespace Wrox.ProCSharp.VenusBank<br />

{<br />

public class SaverAccount: IBankAccount<br />

{<br />

private decimal balance;<br />

public void PayIn(decimal amount)<br />

{<br />

balance += amount;<br />

}<br />

public bool Withdraw(decimal amount)<br />

{<br />

if (balance > = amount)<br />

{<br />

balance -= amount;<br />

return true;<br />

}<br />

Console.WriteLine("Withdrawal attempt failed.");<br />

return false;<br />

}<br />

public decimal Balance<br />

{<br />

get<br />

{<br />

return balance;<br />

}<br />

}<br />

public override string ToString()<br />

{<br />

return String.Format("Venus Bank Saver: Balance = {0,6:C}", balance);<br />

}<br />

}<br />

}<br />

code snippet BankAccounts.cs<br />

It should be pretty obvious what the implementation of this class does. You maintain a private fi eld,<br />

balance , <strong>and</strong> adjust this amount when money is deposited or withdrawn. You display an error message if<br />

an attempt to withdraw money fails because there is insuffi cient money in the account. Notice also that,<br />

because you want to keep the code as simple as possible, you are not implementing extra properties, such as<br />

the account holder ’ s name! In real life that would be pretty essential information, but for this example it ’ s<br />

unnecessarily complicated.<br />

The only really interesting line in this code is the class declaration:<br />

public class SaverAccount: IBankAccount<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!