Вы находитесь на странице: 1из 36

C# Essentials

Robert J. Oberg

Student Guide
Revision 1.0

Object Innovations Course 411


C# Essentials

C# Essentials
Rev. 1.0

Student Guide

Information in this document is subject to change without notice. Companies, names and data
used in examples herein are fictitious unless otherwise noted. No part of this document may be
reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Object Innovations.

Product and company names mentioned herein are the trademarks or registered trademarks of
their respective owners.

Copyright ©2002 Object Innovations, Inc. All rights reserved.

Object Innovations, Inc.


4515 Emory Lane
Charlotte, NC 28211
www.ObjectInnovations.com

Printed in the United States of America.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. ii


All Rights Reserved
C# Essentials

Table of Contents (Overview)


Chapter 1 .NET: What You Need To Know
Chapter 2 C# Overview for the Sophisticated Programmer
Chapter 3 Object-Oriented Programming in C#
Chapter 4 C# and the .NET Framework
Chapter 5 Introduction to Windows Forms

Appendix A Using Visual Studio .NET


Appendix B Learning Resources

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. iii


All Rights Reserved
C# Essentials

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. iv


All Rights Reserved
C# Essentials

Table of Contents (Detailed)

Chapter 1 .NET: What You Need to Know .............................................................. 1


Getting Started ................................................................................................................ 3
.NET: What Is Really Happening ................................................................................... 4
.NET Programming in a Nutshell ................................................................................... 5
.NET Program Example.................................................................................................. 6
Viewing the Assembly.................................................................................................... 7
Viewing Intermediate Language..................................................................................... 8
Understanding .NET ....................................................................................................... 9
.NET Documentation .................................................................................................... 10
Visual C# .NET and GUI Programs ............................................................................. 11
Summary....................................................................................................................... 12
Chapter 2 C# Overview for the Sophisticated Programmer................................. 13
Hello, World ................................................................................................................. 15
Compiling, Running (Command Line) ......................................................................... 16
Program Structure ......................................................................................................... 17
Namespaces................................................................................................................... 20
Variables ....................................................................................................................... 21
Input in C# .................................................................................................................... 22
More About Classes...................................................................................................... 23
InputWrapper Class ...................................................................................................... 24
Sample Program............................................................................................................ 25
Input Wrapper Implementation..................................................................................... 26
Compiling Multiple Files.............................................................................................. 27
Control Structures ......................................................................................................... 28
switch ............................................................................................................................ 29
C# Operators ................................................................................................................. 30
Precedence Table .......................................................................................................... 31
Types in C# ................................................................................................................... 32
Simple Types ................................................................................................................ 33
Types in System Namespace ........................................................................................ 34
Integer Data Types ........................................................................................................ 35
Floating Point Data Types ............................................................................................ 36
Implicit Conversions..................................................................................................... 37
Explicit Conversions..................................................................................................... 38
Boolean Data Type ....................................................................................................... 39
struct.............................................................................................................................. 40
Uninitialized Variables ................................................................................................. 41
Enumeration Types ....................................................................................................... 42
Reference Types............................................................................................................ 43
Class Types ................................................................................................................... 44
object............................................................................................................................. 45

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. v


All Rights Reserved
C# Essentials

string ............................................................................................................................. 46
Classes and Structs........................................................................................................ 47
CHotel Class ................................................................................................................. 48
Hotel Struct ................................................................................................................... 49
Test Program................................................................................................................. 50
RaisePrice Methods ...................................................................................................... 51
Comparing Struct and Class.......................................................................................... 52
Arrays............................................................................................................................ 53
One Dimensional Arrays............................................................................................... 54
System.Array ................................................................................................................ 55
Jagged Arrays................................................................................................................ 56
Rectangular Arrays ....................................................................................................... 57
foreach for Arrays ......................................................................................................... 58
Boxing and Unboxing ................................................................................................... 59
Output in C#.................................................................................................................. 60
Formatting..................................................................................................................... 61
Formatting Example...................................................................................................... 62
Exceptions..................................................................................................................... 63
Exception Example ....................................................................................................... 64
Checked Integer Arithmetic.......................................................................................... 65
Throwing New Exceptions ........................................................................................... 66
finally ............................................................................................................................ 67
System.Exception.......................................................................................................... 68
Lab 2 ............................................................................................................................. 69
Summary....................................................................................................................... 70
Chapter 3 Object-Oriented Programming in C# ................................................... 73
C# Object-Oriented Features ........................................................................................ 75
Encapsulation and Accessors ........................................................................................ 76
Using a Property ........................................................................................................... 77
Indexers......................................................................................................................... 78
Bank Example............................................................................................................... 79
Account Class ............................................................................................................... 80
Namespace .................................................................................................................... 82
Constructors .................................................................................................................. 83
Static Members ............................................................................................................. 84
Static in Main................................................................................................................ 85
Inheritance in C#........................................................................................................... 86
New Version of Base Class........................................................................................... 87
Features of the New Base Class.................................................................................... 88
Derived Class ................................................................................................................ 89
Overriding a Virtual Function....................................................................................... 90
Fragile Base Class Problem .......................................................................................... 91
Access Control and Assemblies.................................................................................... 92
Assembly Example ....................................................................................................... 93
Internal Accessibility .................................................................................................... 94
Building Modules and Assemblies ............................................................................... 95

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. vi


All Rights Reserved
C# Essentials

Lab 3 ............................................................................................................................. 96
Summary....................................................................................................................... 97
Chapter 4 C# and the .NET Framework .............................................................. 101
Components and OO in C# ......................................................................................... 103
Copy Semantics in C#................................................................................................. 104
Arrays.......................................................................................................................... 105
Embedded Objects ...................................................................................................... 106
Copying a Class Instance ............................................................................................ 107
class vs. struct ............................................................................................................. 108
Copying a Struct Instance ........................................................................................... 109
Shallow Copy.............................................................................................................. 110
Shallow Copy Output.................................................................................................. 111
Deep Copy and ICloneable ......................................................................................... 112
Interfaces..................................................................................................................... 113
Generic Interfaces ....................................................................................................... 114
Implementing ICloneable............................................................................................ 115
Using an Interface ....................................................................................................... 116
is Operator................................................................................................................... 117
as Operator .................................................................................................................. 118
.NET and COM........................................................................................................... 119
Arrays and Collections................................................................................................ 120
Lab 4A ........................................................................................................................ 121
Sorting an Array.......................................................................................................... 122
Anatomy of Array.Sort ............................................................................................... 123
Using the is Operator .................................................................................................. 124
The Use of Dynamic Type Checking.......................................................................... 125
Implementing IComparable ........................................................................................ 126
An Incomplete Solution .............................................................................................. 127
Overriding ToString.................................................................................................... 128
Understanding Frameworks ........................................................................................ 129
Delegates..................................................................................................................... 130
Stock Market Simulation ............................................................................................ 131
Running the Simulation .............................................................................................. 132
Delegate Code............................................................................................................. 133
Random Number Generation ...................................................................................... 134
Using the Delegates .................................................................................................... 135
Events.......................................................................................................................... 136
Events in C# and .NET ............................................................................................... 137
Client Side Event Code............................................................................................... 139
Chat Room Example ................................................................................................... 140
Lab 4B......................................................................................................................... 141
Summary..................................................................................................................... 142
Chapter 5 Introduction to Windows Forms ......................................................... 149
Creating a Windows Forms App................................................................................. 151
Windows Forms Event Handling................................................................................ 155
Add Events for a Control ............................................................................................ 156

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. vii


All Rights Reserved
C# Essentials

Events Documentation ................................................................................................ 157


Lab 5 ........................................................................................................................... 158
Summary..................................................................................................................... 159
Appendix A Using Visual Studio .NET .................................................................... 165
Visual Studio .NET..................................................................................................... 167
Overview of VS.NET.................................................................................................. 168
Toolbars ...................................................................................................................... 171
Customizing a Toolbar................................................................................................ 172
Creating a Console Application .................................................................................. 173
Adding a C# File......................................................................................................... 174
Using the Visual Studio Text Editor........................................................................... 175
Build and Run the Bytes Project................................................................................. 176
Project Configurations ................................................................................................ 177
Creating a New Configuration .................................................................................... 178
Setting Build Settings for a Configuration.................................................................. 179
Debugging................................................................................................................... 180
Just-in-Time Debugging ............................................................................................. 181
Standard Debugging -- Breakpoints............................................................................ 182
Standard Debugging -- Watch Variables .................................................................... 183
Debugger Options ....................................................................................................... 184
Stepping with the Debugger........................................................................................ 185
Demo: Stepping with the Debugger........................................................................... 186
The Call Stack............................................................................................................. 187
Summary..................................................................................................................... 188
Appendix B Learning Resources .............................................................................. 189

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. viii


All Rights Reserved
C# Essentials

Chapter 3

Object-Oriented Programming
in C#

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 73


All Rights Reserved
C# Essentials

Object-Oriented Programming in C#

Objectives

After completing this unit you will be able to:


• Give an overview of the object-oriented features of
C#.
• Implement accessors and indexers to provide access
to encapsulated data.
• Describe the use of constructors in C#.
• Use static data and methods.
• Use inheritance and virtual functions.
• Discuss the fragile base class problem and explain the
uses of new and override in C#.
• Describe the access control facilities of C#.
• Work with assemblies in your C# programs.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 74


All Rights Reserved
C# Essentials

C# Object-Oriented Features

• C# is a fully object-oriented language having many


similarities to C++ and Java but also some important
differences.
• C# fully supports encapsulation.
− In addition to methods for accessing encapsulated data, C#
also provides accessors and indexers.
− Besides private and protected access control, C# also has
internal access control, restricting access to an assembly.

• C# has a single inheritance model.


− In this regard C# is more akin to Smalltalk and Java than to
C++.
− All classes (and effectively all data types) in C# inherit from
a root class object.

• C# has the notion of interfaces.


− A class in C# may inherit from only one other class, but it
may support many interfaces.
− We discuss interfaces in the next chapter.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 75


All Rights Reserved
C# Essentials

Encapsulation and Accessors

• It is good programming practice to encapsulate data


within the class and provide public methods to access
the data.
• But it would be nice to be able to access the data “as
if” it were public.
• You can do just that with the C# accessor feature.
public class Course
{
private string title;
private int numStudents = 0;
private string[] students;
private int maxSize;
public string Title
{
get
{
return title;
}
set
{
title = value; // value is keyword
}
}
...
− Title is now a “property”, and has easy to use syntax in a
client program.
− You can implement a read-only property by providing only
the get accessor (and write-only via set byitself).

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 76


All Rights Reserved
C# Essentials

Using a Property

• You can obtain the value of a property using the


standard “dot” notation.
Course c1 = new Course("Intro to C#", 10);
Console.WriteLine(c1.Title); // use the field

• You can also use the property on the right-hand side:


C1.Title = ".NET Programming"; // set the field

• If you are familiar with Visual Basic, you will be very


familiar with properties.
• .NET brings the convenience and ease-of-use of
properties to all .NET languages.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 77


All Rights Reserved
C# Essentials

Indexers

• C# provides another easy to use feature that adds the


capability to access an object as if it were an array.
• Through implementing an indexer on a class, you can
use array notation on both left and right hand sides.
public class Course
{
private string title;
private string[] students;
...
public string this[int i]
{
get
{
return students[i];
}
set
{
students[i] = value;
}
}

Course c1 = new Course("Intro to C#", 10);


Console.WriteLine(c1[0]); // use indexer
c1[0] = "John New Name"; // on LHS

• As with accessors, you can have read-only and write-


only indexers.
• Our example illustrates both accessors and indexers.
− See Course.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 78


All Rights Reserved
C# Essentials

Bank Example

• We will illustrate many object-oriented features of C#


with a simple bank example.
− See Bank\Step1 for the first step.

• The project consists of the following classes, each in


its own file:
− SimpleMath provides operations Add and Subtract.
− Account maintains a private balance exposed through the
public read-only property Balance. Methods Deposit and
Withdraw are provided. There is a read/write property
Owner and a static read/write property BankName.
− InputWrapper class makes input operations more concise.
− TestBank is an interactive console test program.

• Here is the output of a sample run of the program


(run from inside Visual Studio):
Welcome to Fiduciary Bank
balance = 100
Enter command, quit to exit
: deposit
amount: 25
balance = 125
: quit
Press any key to continue

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 79


All Rights Reserved
C# Essentials

Account Class

• Here is the code for the Account class:


// Account.cs

namespace OI.NetCs.Examples
{
using OI.NetCs.Examples;

public class Account


{
private int balance;
private string owner;
static private string bankName =
"Fiduciary Bank";
public Account(int balance)
{
this.balance = balance;
}
public Account(int balance, string owner)
{
this.balance = balance;
this.owner = owner;
}
public void Deposit(int amount)
{
balance = SimpleMath.Add(
balance, amount);
}
public void Withdraw(int amount)
{
balance = SimpleMath.Subtract(
balance, amount);
}

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 80


All Rights Reserved
C# Essentials

Account Class (Cont’d)


public int Balance
{
get
{
return balance;
}
}
public string Owner
{
get
{
return owner;
}
set
{
owner = value;
}
}
static public string BankName
{
get
{
return bankName;
}
set
{
bankName = value;
}
}
}
}

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 81


All Rights Reserved
C# Essentials

Namespace

• The namespace directive places the following


elements inside the OI.NetCs.Examples namespace.
namespace OI.NetCs.Examples
{
...

• The using directive gives us concise access to the


names in the namespace OI.NetCs.Examples.
using OI.NetCs.Examples;

− SimpleMath is in this namespace, so we can use this code:


balance = SimpleMath.Add(balance, amount);

− ... in place of the following code using a fully qualified name:


balance = OI.NetCs.Examples.SimpleMath.Add(
balance, amount);

• Note our use of a hierarchy in our namespace:


− OI is a company/brand (Object Innovations)
− NetCs is an acronym for .NET using C#
− Examples for the example programs

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 82


All Rights Reserved
C# Essentials

Constructors

• An important issue for classes is initialization.


− When an object is created, what initial values are assigned to
the instance data?

• Through a constructor you can initialize an object in


any way you wish.
• A constructor is like a special method which is
automatically called when an object is created.
− A constructor has no return type
− A constructor has the same name as the class
− A constructor may take parameters, which are passed when
invoking new.
− There may be several overloaded constructors.
public Account(int balance)
{
this.balance = balance;
}
public Account(int balance, string owner)
{
this.balance = balance;
this.owner = owner;
}

• Note use of keyword this to refer to current object.


• C# does not have default arguments, so we need two
constructors in this example.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 83


All Rights Reserved
C# Essentials

Static Members

• In C# a static member applies to the entire class, not


to a particular instance of a class.
public class Account
{
private int balance;
private string owner;
static private string bankName = "Fiduciary Bank";
...

− All instances of the class share the same static field (for all
accounts the bank name is the same).

• A static method or property can access static data


members but cannot access non-static data members.
static public string BankName
{
get
{
return bankName;
}
set
{
bankName = value;
}
}

• A client program does not have to instantiate an


instance in order to access a static member. The class
name is used rather than an object instance.
Console.WriteLine("Welcome to {0}",
Account.BankName);

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 84


All Rights Reserved
C# Essentials

Static in Main

• The Main method of a class is static.


− The runtime must be able to invoke Main without
instantiating an object instance.

• This implies that any helper methods you call from


within Main should also be static.
public static void Main()
{
...
private static void show(Account acc)
{
Console.WriteLine("owner = {0}, balance = {1}",
acc.Owner, acc.Balance);
}
private static void help()
{
Console.WriteLine(
"The following commands are available:");
Console.WriteLine(
"\tdeposit -- make a deposit");
Console.WriteLine(
"\twithdraw -- make a withdrawal");
Console.WriteLine(
"\towner -- change owner name");
Console.WriteLine(
"\tshow -- show account information");
Console.WriteLine(
"\tquit -- exit the program");
}

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 85


All Rights Reserved
C# Essentials

Inheritance in C#

• The next step of our bank example illustrates


inheritance.
− See Bank\Step2

• Here is the scenario. We wish to implement a special


kind of an account, a checking account.
− A checking account has a fee based on the number of
transactions
− The fee is waived if the minimum balance is at least a certain
threshold value.

• Here is the design:


− Define a class CheckingAccount derived from the base class
Account.
− Add to the base class some generic code that might apply to
other kinds of accounts besides checking (a counter of
number of transactions and a read-only property that will
return this count).
− Add to the derived class specific code that applies only to
checking accounts (track the minimum balance and compute
fee)

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 86


All Rights Reserved
C# Essentials

New Version of Base Class


public class Account
{
...
protected int numXact = 0; // number of
// transactions
...
virtual public void Deposit(int amount)
{
numXact++;
balance = SimpleMath.Add(balance, amount);
}
virtual public void Withdraw(int amount)
{
numXact++;
balance = SimpleMath.Subtract(
balance, amount);
}
...
public int Transactions
{
get
{
return numXact;
}
}
}

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 87


All Rights Reserved
C# Essentials

Features of the New Base Class

• The class counts the number of transactions with a


private field exposed by a read-only public method.
• This counter is declared protected so that the derived
class can access it.
• The Deposit and Withdraw methods are declared
virtual so that the derived class will be able to
override them.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 88


All Rights Reserved
C# Essentials

Derived Class
public class CheckingAccount : Account
{
private int minBalance;
public CheckingAccount(int bal)
: base(bal)
{
minBalance = balance;
}
public CheckingAccount(int bal, string owner)
: base(bal, owner)
{
minBalance = bal;
}
public int Fee
{
get
{
if (minBalance < 100)
return numXact;
else
return 0;
}
}
...

• The constructors pass parameters to the base class


using the keyword base.
• The Fee property has access to the numXact field in
the base class, because numXact was declared
protected.
− The Fee property is an illustration of a property which is
calculated at runtime and not simply stored in a private field.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 89


All Rights Reserved
C# Essentials

Overriding a Virtual Function

• The Withdraw method in the base class is overridden


to update a minimum balance field, for the purpose of
being able to calculate the fee.
override public void Withdraw(int amount)
{
base.Withdraw(amount);
if (balance < minBalance)
{
minBalance = balance;
}
}

− The base keyword is used to call the base class, as was done
in the constructors.

• Note use of the keyword override to tell the compiler


that you are explicitly overriding an inherited virtual
function.
− Without the override the compiler will issue a warning
message, saying that you are hiding the original method with
a new one.
− If you do want to hide the original method (and defeat any
polymorphic behavior), you can use the new keyword.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 90


All Rights Reserved
C# Essentials

Fragile Base Class Problem

• Inheritance is a powerful feature in object-oriented


programming, but there is a subtle pitfall known as
the “fragile base class problem”.
− Suppose you are responsible for a class D that is derived
from a base class B and you have a method f in your class
(which does not override any such method in the base class).
− Then a new version of class B is released which provides a
new virtual function that happens to match the name and
signature of your f but does something completely different.
− Then polymorphic code which uses a reference to an object
of B and calls f will wind up calling your version of f rather
than the f in the base class.

• This kind of difficulty can arise in a large framework.


Here is a scenario.
− The base class is a Windows class with many methods.
− The derived class implements a custom control, which
responds to its own methods directly and to methods from the
Windows class through inheritance.
− Application code may be called by the framework, and code
that uses your custom control may suddenly not work
properly with the installation of a new version of the
framework that has a new method matching one of yours.

• This problem was an argument for COM not


supporting implementation inheritance. The issue is
addressed in C# and .NET with the override keyword.
Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 91
All Rights Reserved
C# Essentials

Access Control and Assemblies

• Object-oriented languages such as C++, Java and C#


have access control features, which can control access
to a class, method or other entity through keywords
such as public, private and protected.
• C# adds assembly-level access as an option.
• C# has a very rich set of access control modifiers:
public access not restricted
protected access restricted to the containing type or
derived types
internal access restricted to files in the same
assembly
internal protected access restricted to the containing type or
derived types or files in the same assembly
private access restricted to the containing type

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 92


All Rights Reserved
C# Essentials

Assembly Example

• We redo our bank example into three assemblies:


− Account.dll is an assembly consisting of two modules
− Bank.dll is an assembly built from two source files
− TestBank.exe is a test program

Account.DLL Bank.DLL

Account CheckingAccount

SimpleMath Statement

TestBank.EXE

• The code is illustrated in three steps:


− Bank\Step3A is a monolithic program
− Bank\Step3B has three assemblies as shown

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 93


All Rights Reserved
C# Essentials

Internal Accessibility

• Step3A illustrates internal accessibility.


− internal is the default accessibility for a class, and means
accessible within the assembly.
− All Step3A is within one project and so within the same
assembly, so internal classes and members are accessible.
// Statement.cs

using OI.NetDev.Examples;

internal class Statement


{
internal static string GetStatement(
CheckingAccount acc)
{
string s = "Statement for " + acc.Owner +
"\n" + acc.numXact +
" transactions, balance = " +
acc.Balance + ", fee = " + acc.Fee;
return s;
}
}

− The field numXact has the accessibility changed to internal,


so the Statement class can access the field in Account
without going through the public Transactions property.
public class Account
{
...
internal int numXact = 0; // number of
// transactions

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 94


All Rights Reserved
C# Essentials

Building Modules and Assemblies

• Step3B illustrates building multiple assemblies.


− To have a finer degree of control of the build process, we use
command-line build tools.

• First we build Account.dll:


csc /t:module /out:SimpleMath.mod SimpleMath.cs
csc /t:library /addmodule:SimpleMath.mod Account.cs

• Next we build Bank.dll:


csc /t:library /r:Account.dll /out:Bank.dll
CheckingAccount.cs Statement.cs

• Finally we build TestBank.exe:


csc /t:exe /r:Bank.dll /r:Account.dll
/out:TestBank.exe TestBank.cs InputWrapper.cs

• Batch file build.bat automates the build.


• We return to public accessibility in Statement.cs.
public class Statement
{
public static string GetStatement(
CheckingAccount acc)
{
string s = "Statement for " + acc.Owner +
"\n" + acc.Transactions +
" transactions, balance = " + acc.Balance
+ ", fee = " + acc.Fee;
return s;
}
}

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 95


All Rights Reserved
C# Essentials

Lab 3

A Bank Account Hierarchy

In this lab you will practice working with inheritance in C# by


adding a savings account class to a simple bank account hierarchy.
You will also observe the use of virtual and override in C#.

Account

CheckingAccount SavingsAccount

NOTE: This version of the bank example is a little different than


the one used in the lecture.

Detailed instructions are contained in the Lab 3 write-up at the end


of the chapter.

Suggested time: 30 minutes

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 96


All Rights Reserved
C# Essentials

Summary

• C# is a fully object-oriented language with a single


inheritance model.
• You can implement accessors and indexers to provide
access to encapsulated data.
• Constructors are used in C# for initialization.
• Static data and methods apply on a per class basis.
• C# provides inheritance and virtual functions.
• C# provides the new and override keywords, which
can mitigate the fragile base class problem.
• C# has elaborate access control facilities, including
controlling access on an assembly basis.
• You can inherit a class in C# from a class
implemented in another .NET language.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 97


All Rights Reserved
C# Essentials

Lab 3

A Bank Account Hierarchy

Introduction

In this lab you will practice working with inheritance in C# by adding a savings
account class to a simple bank account hierarchy. You will also observe the use of
virtual and override in C#.

Account

CheckingAccount SavingsAccount

NOTE: This version of the bank example is a little different than the one used in the
lecture.

Our example will consists of four classes, each in its own file.

• Account. This class encapsulates a single bank account consisting of an Id, an


Owner, and a Balance. Operations are Deposit and Withdraw. There is also a
field holding the number of transactions, and a GetStatement method is provided
to show the current data for an account. The Account class counts the number of
transactions.
• CheckingAccount. This derived class adds a monthly fee, which is assessed to
checking accounts but not to other accounts.
• SavingsAccount. This derived class adds interest, which is paid to savings ac-
counts but not to other accounts.
• TestAccount. This class provides a hardcoded test program, which instantiates
some classes, performs some transactions, and obtains statements.

Suggested Time: 30 minutes

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 98


All Rights Reserved
C# Essentials

Root Directory: OIC\CsEss

Directories: Labs\Lab3\BankLab (Do your work here)


Chap03\BankLab\Step1 (Backup of starter files)
Chap03\BankLab\Step2 (Answer to first part)
Chap03\BankLab\Step3 (Answer to second part)

Files: Account.cs
SavingsAccount.cs
CheckingAccount.cs
TestAccount.cs.cs

Instructions

1. Build the starter program and study the code. There is only a CheckingAccount class
at this point.

2. Add a SavingsAccount class, derived from Account, to implement the interest


feature. Interest is 6% per year, paid on the minimum balance. You will need to hide the
Withdraw method to update the minimum balance. You will also need to hide the
GetStatement method to show the interest amount as well as the standard information
for a statement.

3. Modify the test program to create a SavingsAccount object and perform a few
transactions, and show the account before and after. Notice that at this point you have
three overloaded ShowAccount helper methods, one for each kind of account. You are
now at Step 2.

4. Modify the program to use virtual methods, and collapse the ShowAccount methods
to a single method that applies polymorphically to all the different kinds of accounts.

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 99


All Rights Reserved
C# Essentials

Rev. 1.0 Copyright © 2002 Object Innovations, Inc. 100


All Rights Reserved

Вам также может понравиться