c Programming Yellow Book 81nbsped Compress
c Programming Yellow Book 81nbsped Compress
c Programming Yellow Book 81nbsped Compress
Yellow Book
Rob Miles
“Cheese” Edition 8.1 December 2019
This page intentionally left blank.
Apart from this text.
And this…….
And this just for version 8.1
i
Introduction 1
Welcome ............................................................................................................................. 1
Reading the notes ................................................................................................................ 1
Getting a copy of the notes and code samples .................................................................... 1
3 Creating Programs 48
3.1 Methods .............................................................................................................. 48
3.2 Variables and Scope ........................................................................................... 58
3.3 Arrays ................................................................................................................. 61
3.4 Exceptions and Errors......................................................................................... 66
3.5 The Switch Construction .................................................................................... 70
3.6 Using Files .......................................................................................................... 73
4 Creating Solutions 79
4.1 Our Case Study: Friendly Bank .......................................................................... 79
4.2 Enumerated Types .............................................................................................. 79
4.3 Structures ............................................................................................................ 82
4.4 Objects, Structures and References .................................................................... 86
4.5 Designing With Objects ..................................................................................... 93
4.6 Static Items ......................................................................................................... 99
4.7 The Construction of Objects ............................................................................. 102
4.8 From Object to Component .............................................................................. 109
4.9 Inheritance ........................................................................................................ 116
4.10 Object Etiquette ................................................................................................ 126
4.11 The power of strings and chars ......................................................................... 131
4.12 Properties .......................................................................................................... 133
4.13 Building a Bank ................................................................................................ 140
i
Call ................................................................................................................................. 199
Class ............................................................................................................................... 199
Code Reuse ..................................................................................................................... 200
Cohesion ......................................................................................................................... 200
Collection........................................................................................................................ 200
Compiler ......................................................................................................................... 200
Component...................................................................................................................... 200
Constructor ..................................................................................................................... 200
Coupling ......................................................................................................................... 201
Creative Laziness ............................................................................................................ 201
Declarative language ...................................................................................................... 201
Delegate .......................................................................................................................... 201
Dependency .................................................................................................................... 202
Event ............................................................................................................................... 202
Exception ........................................................................................................................ 202
Functional Design Specification ..................................................................................... 203
Globally Unique Identifier (GUID) ................................................................................ 203
Hierarchy ........................................................................................................................ 203
Immutable ....................................................................................................................... 203
Inheritance ...................................................................................................................... 203
Interface .......................................................................................................................... 203
Library ............................................................................................................................ 203
Machine code .................................................................................................................. 204
Member ........................................................................................................................... 204
Metadata ......................................................................................................................... 204
Method ............................................................................................................................ 204
Mutator ........................................................................................................................... 204
Namespace ...................................................................................................................... 204
Overload ......................................................................................................................... 204
Override .......................................................................................................................... 205
Portable ........................................................................................................................... 205
Private ............................................................................................................................. 205
Property .......................................................................................................................... 205
Protected ......................................................................................................................... 205
Public .............................................................................................................................. 205
Reference ........................................................................................................................ 205
Signature ......................................................................................................................... 206
Source file ....................................................................................................................... 206
Static ............................................................................................................................... 206
Stream ............................................................................................................................. 206
Structure.......................................................................................................................... 206
Subscript ......................................................................................................................... 206
Syntax Highlighting ........................................................................................................ 207
Test harness .................................................................................................................... 207
This ................................................................................................................................. 207
Typesafe.......................................................................................................................... 207
Unit test........................................................................................................................... 207
Value type ....................................................................................................................... 208
If you find a mistake in the text, please report the error to foundamistake@robmiles.com and I will take a look.
Thanks to Liz, Dina, Lilli, Neil, Richard, William, Don, Bram, Mitch, Jaswinder, Javi, Peter, Justin, James, Mike,
Ian, Papartis, Hassan, Drew and Johan who have all done just that and made the book even better.
Edition 8.1b
Tuesday, 17 December 2019
ii
The cheese was delicious.
iii
Introduction Welcome
Introduction
Welcome
Welcome to the Wonderful World of Rob Miles™. This is a world of bad jokes, puns,
and programming. In this book I'm going to give you a smattering of the C#
programming language. If you have programmed before I'd be grateful if you'd still
read the text. It is worth it just for the jokes and you may actually learn something.
If you have not programmed before, do not worry. Programming is not rocket science
it is, well, programming. The bad news about learning to program is that you get hit
with a lot of ideas and concepts at around the same time when you start, and this can be
confusing. The keys to learning programming are:
Practice – do a lot of programming and force yourself to think about things from a
problem solving point of view
Study – look at programs written by other people. You can learn a lot from studying
code which other folk have created. Figuring out how somebody else did the job is a
great starting point for your solution. And remember that in many cases there is no best
solution, just ones which are better in a particular context, i.e. the fastest, the smallest,
the easiest to use etc.
Persistence – writing programs is hard work. And you have to work hard at it. The
principle reason why most folks don't make it as programmers is that they give up. Not
because they are stupid. However, don't get too persistent. If you haven't solved a
programming problem in 30 minutes you should call time out and seek help. Or at least
walk away from the problem and come back to it. Staying up all night trying to sort out
a problem is not a good plan. It just makes you all irritable in the morning. We will
cover what to do when it all goes wrong later in section 5.9.
1.1 Computers
Before we consider programming, we are going to consider computers. This is an
important thing to do, because it sets the context in which all the issues of
programming itself are placed.
is comparatively easy to change. Software is the voice which says "Computer Running"
in a Star Trek film.
Windows 10 is an example of All computers are sold with some software. Without it they would just be a novel
an operating system. It gives and highly expensive heating system. The software which comes with a computer is
computer programs a often called its Operating System. The Operating System makes the machine usable.
platform on which they can It looks after all the information held on the computer and provides lots of
execute. commands to allow you to manage things. It also lets you run programs, ones you
have written and ones from other people. You will have to learn to talk to an
operating system so that you can create your C# programs and get them to go.
Data Processing
Computers are data processors. Information is fed into them; they do something with it,
and then generate further information. A computer program tells the computer what to
do with the information coming in. A computer works on data in the same way that a
sausage machine works on meat, something is put in one end, some processing is
performed, and something comes out of the other end:
This makes a computer a very A program is unaware of the data it is processing in the same way that a sausage
good "mistake amplifier", as machine is unaware of what meat is. Put a bicycle into a sausage machine and it will
well as a useful thing to try to make sausages out of it. Put invalid data into a computer and it will do equally
blame..... useless things. It is only us people who actually give meaning to the data (see above).
As far as the computer is concerned data is just stuff coming in which has to be
manipulated in some way.
A computer program is just a sequence of instructions which tell a computer what to do
with the data coming in and what form the data sent out will have.
Note that the data processing side of computers, which you might think is entirely
reading and writing numbers, is much more than that, examples of typical data
processing applications are:
Digital Watch: A micro-computer in your watch is taking pulses from a crystal and
requests from buttons, processing this data and producing a display which tells you the
time.
Car: A micro-computer in the engine is taking information from sensors telling it the
current engine speed, road speed, oxygen content of the air, setting of the accelerator
etc and producing voltages out which control the setting of the carburettor, timing of
the spark etc, to optimise the performance of the engine.
CD Player: A computer is taking a signal from the disk and converting it into the
sound that you want to hear. At the same time, it is keeping the laser head precisely
positioned and also monitoring all the buttons in case you want to select another part of
the disk.
Games Console: A computer is taking instructions from the controllers and using
them to manage the artificial world that it is creating for the person playing the game.
Note that some of these data processing applications are merely applying technology to
existing devices to improve the way they work. However, the CD player and games
console could not be made to work without built-in data processing ability.
Most reasonably complex devices contain data processing components to optimise
their performance and some exist only because we can build in intelligence. It is into
this world that we, as software writers are moving. It is important to think of the
business of data processing as much more than working out the company payroll,
reading in numbers and printing out results. These are the traditional uses of
computers.
Note that this "raises the As software engineers it is inevitable that a great deal of our time will be spent fitting
stakes" in that the data processing components into other devices to drive them. You will not press a
consequences of software switch to make something work, you will press a switch to tell a computer to make it
failing could be very work. These embedded systems will make computer users of everybody, and we will
damaging. have to make sure that they are not even aware that there is a computer in there!
You should also remember that seemingly innocuous programs can have life
threatening possibilities. For example, a doctor may use a spread sheet to calculate
doses of drugs for patients. In this case a defect in the program could result in illness or
even death (note that I don't think that doctors actually do this – but you never know..)
customer sign it, and the bottom line is that if you provide a system which behaves
according to the design specification the customer must pay you. Once you have got
your design specification, then you can think about ways of solving the problem. You
might think that this is not necessary if you are writing a program for yourself; there is
no customer to satisfy. This is not true. Writing some form of specification forces you
to think about your problem at a very detailed level. It also forces you to think about
what your system is not going to do and sets the expectations of the customer right at
the start.
Information going in
In the case of our immortal double-glazing problem we can describe the information
as:
• The width of a window.
• The height of the window.
You can see what we need if you take a look at the diagram below:
Height of
Window
Width of Window
The area of the glass is the width multiplied by the height. To make the frame we will
need two pieces of wood the width of the window, and two pieces of wood the height
of the window.
Proving it Works
In a real world you would now create a test which will allow you to prove that the
program works, you could for example say:
“If I give the above program the inputs 2 metres high and 1 metre wide the program
should tell me I need 4 square metres of glass and 19.5 feet of wood.”
The test procedure which is designed for a proper project should test out all possible
states within the program, including the all-important error conditions. In a large
system the person writing the program may have to create a test harness which is fitted
around the program and will allow it to be tested. Both the customer and the supplier
should agree on the number and type of the tests to be performed and then sign a
document describing these.
Testing is a very important part of program development. There is even one
development technique where you write the tests before you write the actual program
that does the job. This is actually a good idea, and one we will explore later. In terms of
code production, you can expect to write as much code to test your solution as is in the
solution itself. Remember this when you are working out how much work is involved
in a particular job.
Getting Paid
Better yet, set up a phased At this point the supplier knows that if a system is created which will pass all the
payment system so that you tests the customer will have no option but to pay for the work! Note also that because
get some money as the system the design and test procedures have been frozen, there is no ambiguity which can
is developed. lead to the customer requesting changes to the work although of course this can still
happen!
The good news for the developer is that if changes are requested these can be viewed in
the context of additional work, for which they can expect to be paid.
Customer Involvement
Note also in a "proper" system the customer will expect to be consulted as to how the
program will interact with the user, sometimes even down to the colour of the letters on
the display! Remember that one of the most dangerous things that a programmer can
think is "This is what he wants"! The precise interaction with the user - what the
program does when an error is encountered, how the information is presented etc., is
something which the customer is guaranteed to have strong opinions about. Ideally all
this information should be put into the specification, which should include layouts of
the screens and details of which keys should be pressed at each stage. Quite often
prototypes will be used to get an idea of how the program should look and feel.
Fact: If you expect to derive If this seems that you are getting the customer to help you write the program then
the specification as the you are exactly right! Your customer may have expected you to take the description
project goes on either you will of the problem and go into your back room - to emerge later with the perfect solution
fail to do the job, or you will to the problem. This is not going to happen. What will happen is that you will come
end up performing five times up with something which is about 60% right. The customer will tell you which bits
the work! look OK and which bits need to be changed. You then go back into your back room,
muttering under your breath, and emerge with another system to be approved. Again,
Rob's law says that 60% of the wrong 40% will now be OK, so you accept changes
for the last little bit and again retreat to your keyboard....
The customer thinks that this is great, reminiscent of a posh tailor who produces the
perfect fit after numerous alterations. All the customer does is look at something,
suggests changes and then wait for the next version to find something wrong with.
They will get a bit upset when the delivery deadline goes by without a finished product
appearing but they can always cheer themselves up again by suing you.
Actually, we have come full circle here, because I did mention earlier that prototyping
is a good way to build a system when you are not clear on the initial specification.
However, if you are going to use prototypes it is a good thing to plan for this from the
start rather than ending up doing extra work because your initial understanding of the
problem was wrong.
Fact: More implementations If your insistence on a cast iron specification forces the customer to think about
fail because of inadequate exactly what the system is supposed to do and how it will work, all to the better. The
specification than for any customer may well say "But I am paying you to be the computer expert, I know
other reason! nothing about these machines". This is no excuse. Explain the benefits of "Right
First Time" technology and if that doesn't work produce a revolver and force the
issue!
Again, if I could underline in red I would: All the above apply if you are writing the
program for yourself. You are your own worst customer!
You may think that I am labouring a point here; the kind of simple systems we are
going to create as we learn to program are going to be so trivial that the above
techniques are far too long winded. You are wrong. One very good reason for doing
this kind of thing is that it gets most of the program written for you - often with the
help of the customer. When we start with our double glazing program, we now know
that we have to:
read in the width
verify the value
read in the height
verify the value
calculate width times height times 2 and print it
calculate ( width + height ) * 2 * 3.25 and print it
The programming portion of the job is now simply converting the above description
into a language which can be used in a computer.......
Programming languages get around both of these problems. They are simple enough to
be made sense of by computer programs and they reduce ambiguity.
1.4 C#
There are literally hundreds We are going to learn a language called C# (pronounced C sharp). If you ever make
of programming languages the mistake of calling the language C hash you will show your ignorance straight
around; you will need to know away! C# is a very flexible and powerful programming language with an interesting
at least 3! history. It was developed by Microsoft Corporation for a variety of reasons, some
technical, some political and others marketing.
C# bears a strong resemblance to the C++ and Java programming languages, having
borrowed (or improved) features provided by these languages. The origins of both Java
and C++ can be traced back to a language called C, which is a highly dangerous and
entertaining language which was invented in the early 1970s. C is famous as the
language the UNIX operating system was written in, and was specially designed for
this.
1.4.1 Dangerous C
I referred to C as a dangerous language. So what do I mean by that? Consider the chain
saw. If I, Rob Miles, want to use a chainsaw I will hire one from a shop. As I am not an
experienced chain saw user I would expect it to come with lots of built in safety
features such as guards and automatic cut outs. These will make me much safer with
the thing but will probably limit the usefulness of the tool, i.e. because of all the safety
stuff I might not be able to cut down certain kinds of tree. If I was a real lumberjack I
would go out and buy a professional chainsaw which has no safety features whatsoever
but can be used to cut down most anything. If I make a mistake with the professional
tool I could quite easily lose my leg, something the amateur machine would not let
happen.
In programming terms what this means is that C lacks some safety features provided by
other programming languages. This makes the language much more flexible.
However, if I do something stupid C will not stop me, so I have a much greater chance
of crashing the computer with a C program than I do with a safer language.
1.4.2 Safe C#
The C# language attempts to get the best of both worlds in this respect. A C# program
can contain managed or unmanaged parts. The managed code is fussed over by the
system which runs it. This makes sure that it is hard (but probably not impossible) to
crash your computer running managed code. However, all this fussing comes at a price,
causing your programs to run more slowly.
To get the maximum possible performance, and enable direct access to parts of the
underlying computer system, you can mark your programs as unmanaged. An
unmanaged program goes faster, but if it crashes it is capable of taking the computer
with it. Switching to unmanaged mode is analogous to removing the guard from your
new chainsaw because it gets in the way.
C# is a great language to start learning with as the managed parts will make it easier for
you to understand what has happened when your programs go wrong.
I'm not going to go into details of how to download and install the .NET framework;
that is for other documents, I am going to assume that you are using a computer which
has a text editor (usually Notepad) and the .NET framework installed.
Objects
Some of the things in the programs that we write are objects that are part of the
framework we are using. To continue our cooking analogy, these are things like mixing
bowls and ovens, which are used during the cooking process. The names of objects will
be given in a different shade of blue in some of the listings in this text.
using System;
class GlazerCalc
{
static void Main()
{
double width, height, woodLength, glassArea;
string widthString, heightString;
widthString = Console.ReadLine();
width = double.Parse(widthString);
heightString = Console.ReadLine();
height = double.Parse(heightString);
using System;
A big part of learning to This is an instruction to the C# compiler to tell it that we want to use things from the
program is learning how to System namespace. A namespace is a place where particular names have meaning.
use all the additional features We have namespaces in our conversations too, if I am using the "Football"
of the system which support namespace and I say “That team is really on fire” I'm saying something good. If I
your programs. am using the "Firefighter" namespace I'm saying something less good.
In the case of C# the System namespace is where lots of useful things are described.
One of these useful things provided with C# is the Console class which will let me
write things which will appear on the screen in front of the user. If I want to just refer
to this as Console I have to tell the compiler I'm using the System namespace. This
means that if I refer to something by a particular name the compiler will look in
System to see if there is anything matching that name. We will use other namespaces
later on.
class GlazerCalc
Classes are the basis of object A C# program is made up of one or more classes. A class is a container which holds
oriented programming, as we data and program code to do a particular job. In the case of our double glazing
shall see later. calculator the class just contains a single method which will work out our wood
lengths and glass area, but a class can contain much more than that if it needs to.
You need to invent an identifier for every class that you create. I've called ours
GlazerCalc since this reflects what it does. For now, don't worry too much about
classes; just make sure that you pick sensible names for the classes that you create.
Oh, and one other thing. There is a convention that the name of the file which contains
a particular class should match the class itself, in other words the program above
should be held in a file called GlazerCalc.cs.
static
This keyword makes sure that the method which follows is always present, i.e. the
word static in this context means "is part of the enclosing class and is always
here". When we get to consider objects we will find that this little keyword has all
kinds of interesting ramifications. But for now I'd be grateful if you'd just make sure
that you put it here in order to make your programs work properly.
void
A void is nothing. In programming terms the void keyword means that the method
we are about to describe does not return anything of interest to us. The method will
just do a job and then finish. In some cases we write methods which return a result
(in fact we will use such a method later in the program).
However, in order to stop someone else accidentally making use of the value
returned by our Main method, we are explicitly stating that it returns nothing. This
makes our programs safer, in that the compiler now knows that if someone tries to
use the value returned by this method, this must be a mistake.
Main
You choose the names of your methods to reflect what they are going to do for you.
Except for Main. This method (and there must be one, and only one such method) is
where your program starts running. When your program is loaded and run the first
method given control is the one called Main. If you miss out the Main method the
system quite literally does not know where to start.
()
This is a pair of brackets enclosing nothing. This may sound stupid, but actually tells
the compiler that the method Main has no parameters. A parameter to a method gives
the method something to work on. When you define a method you can tell C# that it
works on one or more things, for example sin(x) could work on a floating point
value of angle x. We will cover methods in very great detail later in this document.
{
This is a brace. As the name implies, braces come in packs of two, i.e. for every open
brace there must be a matching close. Braces allow programmers to lump pieces of
program together. Such a lump of program is often called a block. A block can contain
the declaration of variables used within it, followed by a sequence of program
statements which are executed in order. In this case the braces enclose the working
parts of the method Main.
When the compiler sees the matching close brace at the end it knows that it has reached
the end of the method and can look for another (if any). The effects of an un-paired
brace are invariably fatal....
double
By now you probably feel that you need a drink. But that is not what double means in
this context. What it means is "double precision floating point number".
Our program needs to remember certain values as it runs. Notably it will read in values
for the width and height of the windows and then calculate and print values for the
glass area and wood length. C# calls the places where values are put variables. At the
beginning of any block you can tell C# that you want to reserve some space to hold
some data values. Each item can hold a particular kind of value. Essentially, C# can
handle three types of data, floating point numbers, integer numbers and text (i.e. letters,
digits and punctuation). The process of creating a variable is called declaring the
variable.
A double variable can hold a You declare some variables of a particular type by giving the type of the data,
very wide range of values to a followed by a list of the names you want the variables to have. We are using the type
very high precision. double for now. Later we will use other types.
;
The semicolon marks the end of the list of variable names, and also the end of that
declaration statement. All statements in C# programs are separated by the ; character,
this helps to keep the compiler on the right track.
The ; character is actually very important. It tells the compiler where a given statement
ends. If the compiler does not find one of these where it expects to see one it will
produce an error. You can equate these characters with the sprocket holes in film, they
keep everything synchronised.
widthString =
This is an assignment statement. In this C# statement we are going to change the value
in a variable. Our program is going to read a line of text from the user and place the
result in the variable we have called widthString. Remember that a variable is
simply a named box of a particular size, which can hold a single data item (in this case
a string of text).
A good proportion of your programs will be instructions to assign new values to
variables, as the various results are calculated. C# uses the = character to make
assignments happen. The first part of this statement is the name of a previously defined
variable. This is followed by the = character which I call the gozzinta. I call it that
because the value on the right gozzinta (goes into) the variable on the left. Sorry.
Console.
On the right of the equals we have the thing which is going to be assigned to
widthString. In this case the result is going to be the string returned by the method
ReadLine. This method is part of an object called Console which looks after the
user input and output. The full stop (.) separates the object identifier from the method
identifier.
ReadLine
This indicates that the ReadLine method is to be invoked. This asks the running
program to dash off, do whatever statements there are in this method, and then come
back. Methods are a way in which you can break up your program into a number of
chunks, each of which has a particular job. They also mean that you only have to write
a particular piece of code once, put it in a method, and then call that method whenever
you want that particular job done. The C# system contains a number of built in
methods to do things for our programs. ReadLine is one of these.
When this program runs the ReadLine method is invoked (or called). It will wait for
the user to enter a line of text and press the Enter key. Whatever is typed in is then
returned as a string by the ReadLine method. The result of the method call is placed in
the widthString variable.
()
A method call is followed by the parameters to the method. A parameter is something
that is passed into a method for it to work on. Think of it as raw materials for a process
of some kind. In the case of ReadLine it has no raw materials; it is going to fetch the
information from the user who will type it in. However, we still have to provide the list
of parameters even if it is empty.
;
We have seen the semi-colon before. It marks the end of a statement in our program.
width =
This is another assignment (Mr. Phelps/Hawke1). The variable width is being given a
value. Many statements in your programs will simply be moving data around and
performing actions on it.
double.
But the rest of the statement looks a bit scary. In fact it is not too tricky. We are asking
Mr. double (the thing responsible holding for double precision floating point
numbers) to do a little job for us. In this case the little job is "take the string held by
widthString and convert it into a double precision floating point number". Mr.
double provides this ability by exposing a method called Parse.
Note that there is nothing wrong or naughty about something in C# exposing its
methods. It is how we get things done for us. When you come to design larger
programs you will find that the best way to do this is to create components which
expose methods to get the job done. The whole of the C# library set is provided as a
series of methods and one of the things that you will have to get to grips with is where
the methods are and how to use them. As with many things in life, the trick is knowing
who to ask…
Parse
The Parse method has the job of converting the string it has been given into a double
precision floating point number. To do this it must look along the string, pull out each
digit in turn and then calculate the actual value, as in "12" means a ten and two units.
This process of looking along things is often called parsing. Hence the name of the
method we are using. The method is given the string that is to be parsed and returns the
number that it has found.
Note that this gives significant potential for evil, in that if the user doesn’t type in a
value or types something like "Twenty Five" the Parse method call will not be able to
resolve a number and will fail as a result. How it fails, and how you can resolve this
failure, will be left for a future section in order to add more excitement to this text.
(widthString);
We have seen that a call of a method must be followed by the raw materials
(parameters) for that method. In the case of ReadLine there are no parameters, but we
still need to supply an empty list to indicate this. In the case of Parse the method
needs to be given the string that it is to work on. We do this by putting the name of the
string variable containing the text (widthString) into the brackets as above. The
value of the information in widthString (i.e. the text that the user has typed in) is
passed into the Parse method for it to work on and extract the number from.
1
Obscure movie/TV show reference for you there folks.
heightString = Console.ReadLine();
height = double.Parse(heightString);
These two statements simply repeat the process of reading in the text of the height
value and then converting it into a double precision value holding the height of the
window.
Console.WriteLine
This is a call of a method, just like the ReadLine method, except that this one takes
what it is given and then prints it out on the console.
(
This is the start of the parameters for this method call. We have seen these used in the
calls of Parse and also ReadLine
+
Plus is an addition operator. We have seen it applied to add two integers together.
However, the plus here means something completely different2. In this case it means
"add two strings together".
2
Another TV show reference
You will have to get used to the idea of context in your programs. We have seen this
with namespaces. Here it is with operators. The C# system uses the context of an
operation to decide what to do. In the case of the previous +, between two double
precision floating point numbers it means "do a sum". Here it has a string on the left
hand side. This means that it is going to perform string concatenation rather than
mathematical addition.
woodLength
This is another example of context at work. Previously we have used woodLength as a
numeric representation of a value, in this program the length of the wood required.
However, in the context it is being used at the moment (added to the end of a string) it
cannot work like that.
The C# compiler must therefore ask the woodLength data item to convert itself into a
string so it can be used correctly in this position. Fortunately it can do this, and so the
program works as you would expect.
It is very important that you understand precisely what is going on here. Consider:
Console.WriteLine ( 2.0 + 3.0 );
This would perform a numeric calculation (2.0 + 3.0) and produce a double precision
floating point value. This result value would then be asked to provide a string version
of itself to be printed, giving the output:
5
But the line of code:
Console.WriteLine ( "2.0" + 3.0 );
Would regard the + as concatenating two strings. It would ask the value 3 to convert
itself into a string (sounds strange – but this is what happens. It would then produce the
output:
2.03
The string "2.0" has the text of the value 3.0 added on the end. This difference in
behaviour is all because of the context of the operation that is being performed.
You can think of all of the variables in our program being tagged with metadata (there
is that word again) which the compiler uses to decide what to do with them. The
variable heightString is tagged with information that says "this is a string, use a
plus with this and you concatenate". The variable woodLength is tagged with
metadata which says "this is a double precision floating point value, use a plus with
this and you perform arithmetic".
+ " feet"
Another concatenation here. We are adding the word feet on the end. Whenever I print
a value out I always put the units on the end. This makes it much easier to ensure that
the value makes sense.
)
The bracket marks the end of the parameter being constructed for the WriteLine
method call. When the method is called the program first assembles a completed string
out of all the components, adding (or concatenating) them to produce a single result. It
then passes the resulting string value into the method which will print it out on the
console.
;
The semi-colon marks the end of this statement.
}
Now for some really important stuff. The program is essentially complete. We have
added all the behaviours that we need. However, the compiler still needs to be told that
we have reached the end of the program. This first close brace marks the end of the
block of code which is the body of the Main method. A block of code starts with a {
and ends with a }. When the compiler sees this it says to itself "that is the end of the
Main method".
}
The second closing brace has an equally important job to the first. It marks the end of
the class GlazerCalc. In C# everything exists inside a class. A class is a container for
a whole bunch of things, including methods. If we want to (and we will do this later)
we may put a number of methods into a class. For now however, we only want the one
method in the class. And so we use the second closing brace to mark the end of the
class itself.
Punctuation
That marks the end of our program. One of the things that you will have noticed is that
there is an awful lot of punctuation in there. This is vital and must be supplied exactly
as C# wants it, otherwise you will get what is called a compilation error. This simply
indicates that the compiler is too stupid to make sense of what you have given it!
You will quickly get used to hunting for and spotting compilation errors. One of the
things you will find is that the compiler does not always detect the error where it takes
place; consider the effect of missing out a "(" character. However, note that just
because the compiler reckons your program is OK is no guarantee of it doing what you
want!
Another thing to remember is that the layout of the program does not bother the
compiler, the following is just as valid:
using System;class GlazerCalc{static void Main(){double width, height,
woodLength, glassArea;string widthString, heightString;widthString =
Console.ReadLine();width = double.Parse(widthString);heightString =
Console.ReadLine();height = double.Parse(heightString);woodLength = 2 * ( width
+ height ) * 3.25 ;glassArea = 2 * ( width * height ) ;Console.WriteLine (
"The length of the wood is " + woodLength + " feet" ) ;Console.WriteLine(
"The area of the glass is " + glassArea + " square metres" ) ;}}
- although if anyone writes a program which is laid out this way they will get a smart
rap on the knuckles from me!
Note that we can go one The standard integer type, int, can hold frighteningly large numbers in C#, in the
further negative than range -2,147,483,648 to 2,147,483,647. If you want to hold even larger integers than
positive. This is because this (although I've no idea why you'd want this) there is a long version.
the numbers are stored
using "2's complement" An example of an integer variable would be something which kept track of the number
notation. of sheep in a field:
int numberOfSheep = 0;
This creates a variable which could keep track of over two thousand million sheep! It
also sets the initial value to 0. Using int (which can hold negative values) lets a
program manipulate "negative sheep" which is probably not meaningful (unless you
run a sheep bank of course and let people borrow them). Remember that the language
itself is unaware of any such considerations. If you want to make sure that we never
have more than 1,000 sheep and the number of sheep never goes negative you must
add this behaviour yourself.
When you edit your program source using Visual Studio (or another code editor that
supports syntax highlighting) you will find that the names of types that are built into
the C# language (such as int and float) are displayed in blue, as shown above.
In this statement the 127 is regarded as an sbyte literal, not an integer. This means
that if I do something stupid:
sbyte tinyVal = 128;
(the maximum value that an sbyte can hold is 127) the compiler will detect that I
have made a mistake and the program will not compile.
char variables
A char is a type of variable which can hold a single character. A character is what you
get when you press a key on a keyboard or display a single character on the screen. C#
uses a character set called UNICODE which can handle over 65,000 different character
designs including a wide range of foreign characters.
An example of a character variable could be something which held the command key
that the user has just pressed:
char commandKey;
string variables
A type of box which can hold a string of text. In C# a string can be very short, for
example "Rob", or it can be very long, for example "War and Peace" (that is the book
not the three words). A string variable can hold a line of text. However, because there
are special characters which mean "take a new line" (see above) it is perfectly possible
for a single string to hold a large number of lines of text.
An example of a string variable could be something which holds the line that the user
has just typed in:
string commandLine;
2.2.5 Identifiers
In C# an identifier is a name that the programmer chooses for something in the
program. The name of a variable is more properly called an identifier. We will see
other places where we create identifiers. C# has some rules about what constitutes a
valid identifier:
• All identifiers names must start with a letter.
• After the letter you can have either letters or numbers or the underscore
"_" character.
Upper and lower case letters are different, i.e. Fred and fred are different identifiers.
Here are a few example declarations, one of which are not valid (see if you can guess
which one and why):
int fred ;
float jim ;
char 29yesitsme ;
One of the golden rules of programming, along with "always use the keyboard with the
keys uppermost" is:
Always give your variables meaningful names.
According to the Mills and Boon romances that I have read, the best relationships are
meaningful ones.
The convention in C# for the kind of variables that we are creating at the moment is to
mix upper and lower case letters so that each word in the identifier starts with a capital:
float averageIceCreamPriceInPence;
This is sometimes called camel case, presumably because of the "humps" in the
identifier which are caused by the capitals.
averageIceCreamPriceInPence =
computedTotalPriceInPence / numberOfIceCreams;
Expressions
An expression is something which can be evaluated to produce a result. We can then
use the result as we like in our program. Expressions can be as simple as a single value
and as complex as a large calculation. They are made up of two things, operators and
operands.
Operands
Operands are things the operators work on. They are usually literal values or the
identifiers of variables. In the program above first, second, third are identifiers
and 2 is a literal value. A literal value is something which is literally there in the code.
A literal value has a type associated with it by the compiler.
Operators
Operators are the things which do the work: They specify the operation to be
performed on the operands. Most operators work on two operands, one each side. In
the program above + is the only operator.
Here are a few example expressions:
2 + 3 * 4
-1 + 3
(2 + 3) * 4
These expressions are worked out (evaluated) by C# moving from left to right, just as
you would yourself. Again, just as in traditional maths all the multiplication and
division is performed first in an expression, followed by the addition and subtraction.
C# does this by giving each operator a priority. When C# works out an expression it
looks along it for all the operators with the highest priority and does them first. It then
looks for the next ones down and so on until the final result is obtained. Note that this
means that the first expression above will therefore return 14 and not 20.
If you want to force the order in which things are worked out you can put brackets
around the things you want done first, as in the final example. You can put brackets
inside brackets if you want, provided you make sure that you have as many open ones
as close ones. Being a simple soul I tend to make things very clear by putting brackets
around everything.
It is probably not worth getting too worked up about this expression evaluation as posh
people call it; generally speaking things tend to be worked out how you would expect
them.
For completeness here is a list of all operators, what they do and their precedence
(priority). I am listing the operators with the highest priority first.
- unary minus, the minus that C# finds in negative numbers, e.g. -1.
Unary means applying to only one item.
* multiplication, note the use of the * rather than the more
mathematically correct but confusing x.
/ division, because of the difficulty of drawing one number above
another on a screen we use this character instead
+ Addition.
- subtraction. Note that we use exactly the same character as for unary
minus.
This is not a complete list of all the operators available, but it will do for now. Because
these operators work on numbers they are often called the numeric operators. But of
course you should remember that some of them (for example +) can be used between
other types of data as well. It is also possible to use operators in a way which causes
values to be moved from one type to another. This can cause problems as we shall see
now.
to perform will cause data to be lost from the program. It considers every operation in
terms of "widening and narrowing" values.
Casting
We can force C# to regard a value as being of a certain type by the use of casting. A
cast takes the form of an additional instruction to the compiler to force it to regard a
value in a particular way. You cast a value by putting the type you want to see there in
brackets before it. For example:
double d = 1.5;
float f = (float) d ;
In the above code the message to the compiler is "I don't care that this assignment
could cause the loss of information. I, as the writer of the program, will take the
responsibility of making sure that the program works correctly". You can regard
casting as the compiler's way of washing its hands of the problem. If a program fails
because data is lost it is not because the compiler did something silly.
As we saw above, each type of variable has a particular range of possible values, and
the range of floating point values is much greater than that for integers. This means that
if you do things like this:
int i ;
i = (int) 123456781234567890.999 ;
I do not think of this as a - the cast is doomed to fail. The value which gets placed in i will be invalid. Nothing
failing in C#. It gives you in C# checks for mistakes like this. It is up to you when you write your program to
great flexibility, at the cost of make sure that you never exceed the range of the data types you are using - the
assuming you know what you program will not notice but the user certainly will!
are doing....
The way that an operator behaves depends on the context of its use. Later on we will
see that the + operator, which normally performs a numeric calculation, can be used
between strings to concatenate them together, i.e. "Ro" + "b" would give the result
"Rob".
If you want complete control over the particular kind of operator the compiler will
generate for you the program must contain explicit casts to set the correct context for
the operator.
using System;
class CastDemo
{
static void Main ()
{
int i = 3, j = 2 ;
float fraction ;
fraction = (float) i / (float) j ;
Console.WriteLine ( "fraction : " + fraction ) ;
}
}
Code Sample 03 Casting Demo
The (float) cast in the above tells the compiler to regard the values in the integer
variables as floating point ones, so that we get 1.5 printed out rather than 1.
needed). One way to solve this is to add 99 to the number of tablets before you
perform the division, forcing the number of bottles required to "round up" any number
of tablets greater than 0. This makes the active part of the program as follows:
int bottleCount = ((tabletCount + 99) / 100) ;
The interesting thing here is that the program for the chemist is actually just a variation
on the program for the double glazing salesman. Both conform to a pattern of
behaviour (read data in, process it, print it out) which is common to many applications.
Any time that you are asked to write a program that reads in some data, works out
some answers and then prints out the result you can make use of this pattern.
Part of the skill of a programmer is identifying the nature of a problem in terms of the
best pattern to be used to solve it.
• It should be clear who wrote it, and when it was last changed. If you write
something good you should put your name on it. If you change what you
wrote you should add information about the changes that you made and why.
A big part of a well written program is the comments that the programmer puts there. A
program without comments is a bit like an aeroplane which has an autopilot but no
windows. There is a chance that it might take you to the right place, but it will be very
hard to tell where it is going from the inside.
Block Comments
When the C# compiler sees the "/*" sequence which means the start of a comment it
says to itself:
“Aha! Here is a piece of information for greater minds than mine to ponder. I will
ignore everything following until I see a */ which closes the comment.”
As an example:
/* This program works out glass and wood required for
a double glazing salesman. */
Be generous with your comments. They help to make your program much easier to
understand. You will be very surprised to find that you quickly forget how you got
your program to work. You can also use comments to keep people informed of the
particular version of the program, when it was last modified and why, and the name of
the programmer who wrote it – even if it was you.
If you are using an editor that supports syntax highlighting you will find that comments
are usually displayed in green.
Line Comments
Another form of comment makes use of the // sequence. This marks the start of a
comment which extends to the end of that particular line of code. It is useful for putting
a quick note on the end of a statement:
position = position + 1 ; // move on to the next customer
I've annotated the statement to give the reader extra information about what it actually
does.
This is plain insulting to the reader I reckon. If you chose sensible identifiers you should find that your program
will express most of what it does directly from the code itself.
1. straight line
2. chosen depending on a given condition
3. repeated according to a given condition
Every program ever written is composed of the three elements above, and very little
else! You can use this to good effect when designing an overall view of how your
program is going to work. At the moment we have only considered programs which
run in a straight line and then stop. The path which a program follows is sometimes
called its "thread of execution". When you call a method the thread of execution is
transferred into the method until it is complete.
Conditional Execution - if
The program above to work out the wood and glass for our glazing man is nice; in fact
our customer will probably be quite pleased with it. However, it is not perfect. The
problem is not with the program, but with the user.
If you give the program a window width of -1 it goes ahead and works out a stupid
result. Our program does not have any checking for invalid widths and heights. The
user might have grounds for complaint if the program fails to recognise that he has
given a stupid value, in fact a number of cases are currently being fought in the United
States courts where a program has failed to recognise invalid data, produced garbage
and caused a lot of damage.
What we want to do is notice the really stupid replies and tell the user that he has done
something dubious. In our program specification, which we give the customer, we have
said something like (this is our metadata):
The program will reject window dimensions outside the following ranges:
width less than 0.5 metres
width greater than 5.0 metres
height less than 0.75 metres
height greater than 3.0 metres
This means that we have done all we can; If the program gets 1 rather than 10 for the
width then that is the users' problem, the important thing from our point of view is that
the above specification stops us from being sued!
In order to allow us to do this the program must notice naughty values and reject them.
To do this we can use the construction:
if (condition)
statement or block we do if the condition is true
else
statement or block we do if the condition is false
The condition determines what happens in the program. So what do we mean by a
condition? C# has a way in which true and false can be explicitly stated in a program.
We have already seen that the bool type is used to store this logical state.
We can create conditions which return a logical result. These are called "logical
conditions". Which is logical. The simplest condition is simply the value true or false,
for example:
if (true)
Console.WriteLine ( "hello mum" ) ;
This is valid, although rather useless as the condition is always true, so "hello mum"
is always printed (note that we left the else portion off - this is OK because it is
optional).
==
equals. If the left hand side and the right hand side are equal the expression has the
value true. If they are not equal the value is false.
4 == 5
- would evaluate to false. Note that it is not particularly meaningful to compare
floating point variables to see if they hold exactly the same values. Because of the fact
that they are held to limited precision you might find that conditions fail when they
should not for example the following equation:
x = 3.0 * (1.0 / 3.0) ;
- may well result in x containing 0.99999999, which would mean that:
x == 1.0
If you want to compare - would be false - even though mathematically the test should evaluate to true.
floating point values subtract
them and see if the difference !=
is very small.
not equal. The reverse of equals. If the operands are not equal the expression has the
value true, if they are equal it has the value false. Again, this test is not advisable
for use with floating point numbers.
<
less than. If the operand on the left is less than the one on the right the value of the
expression is true. If the left hand operand is larger than or equal to the right hand one
the expression gives false. It is quite valid to compare floating point numbers in this
way.
>
greater than. If the operand on the left is greater than the one on the right the result is
true. If the operand on the left is less than or equal to the one on the right the result is
false.
<=
less than or equal to. If the operand on the left is less than or equal to the one on the
right you get true, otherwise you get false.
>=
greater than or equal to. If the operand on the left is greater than or equal to the one
on the right you get true, otherwise it is false.
!
not. This can be used to invert a particular value or expression, for example you can
say !true, which is false, or you could say: !(x==y) - which means the same as
(x!=y). You use not when you want to invert the sense of an expression.
&&
and. If the operands on each side of the && are true the result of the && is true. If one
of them is false the result is false, for example
||
or. If either of the operands each side of the || are true the result of the expression is
true. The expression is only false if both operands are false, for example:
width < 0.5 || width > 5.0
De Morgan’s theorem is the - this would be true if the width was invalid. We are saying that the width is invalid
basis of this. if it is less than the minimum or larger than the maximum. Note that to reverse the
sense of the condition (i.e. true when the value is invalid) we not only have to change
the > into <= in each expression, but also change the && into an ||.
Using these operators in conjunction with the if construction we can make decisions
and change what our program will do in response to the data we get.
program I will include some magic numbers which give the maximum and minimum
values for heights and widths. These come from the metadata I was so careful to gather
when I wrote the specification for the program.
Now I could just use the values 0.5, 5.0, 0.75 and 3.0 - but these are not packed
with meaning and make the program hard to change. If, for some reason, my maximum
glass size becomes 4.5 metres I have to look all through the program and change only
the appropriate values. I do not like the idea of "magic numbers" in programs, what I
would like to do is replace each number with something a bit more meaningful.
We can do this by making a variable which is constant, i.e. it can never be changed.
const double PI=3.141592654;
This means that you can do things like:
circ = rad * 2 * PI ;
This is both more meaningful (we are using PI not some anonymous value) and makes
the program quicker to write. Anywhere you use a magic number you should use a
constant of this form, for example:
const double MAX_WIDTH = 5.0 ;
This makes your programs much easier to read, and also much easier to change.
There is a convention that you always give constant variables names which are
expressed in CAPITAL LETTERS. This is so that when you read your program you
can tell which things have been defined.
We can therefore modify our double glazing program as follows:
using System;
class GlazerCalc
{
static void Main()
{
double width, height, woodLength, glassArea;
2.3.3 Loops
Conditional statements allow you to do something if a given condition is true. However
often you want to repeat something while a particular condition is true, or a given
number of times.
C# has three ways of doing this, depending on precisely what you are trying to do.
Note that we get three methods not because we need three but because they make life
easier when you write the program (a bit like an attachment to our chainsaw to allow it
to perform a particular task more easily). Most of the skill of programming involves
picking the right tool or attachment to do the job in hand. (the rest is finding out why
the tool didn't do what you expected it to!).
In the case of our program we want to repeatedly get numbers in while we are getting
invalid ones, i.e. giving a proper number should cause our loop to stop. This means that
if we get the number correctly first time the loop will execute just once. You might
think that I have pulled a fast one here; all I have done is change:
Get values until you see one which is OK
into
Get values while they are not OK
Part of the art of programming is changing the way that you think about the problem to
suit the way that the programming language can be told to solve it.
do -- while loop
In the case of our little C# program we use the do -- while construction which looks
like this:
do
statement or block
while (condition) ;
This allows us to repeat a chunk of code until the condition at the end becomes false.
Note that the test is performed after the statement or block, i.e. even if the test is bound
to fail the statement is performed once.
A condition in this context is exactly the same as the condition in an if construction,
raising the intriguing possibility of programs like:
using System;
class Forever
{
public static void Main ()
{
do
Console.WriteLine ( "Hello mum" ) ;
while ( true );
}
}
Code Sample 05 Infinite loop
This is a perfectly legal C# program. How long it will run for is an interesting question,
the answer contains elements of human psychology, energy futures and cosmology, i.e.
it will run until:
while loop
Sometimes you want to decide whether or not to repeat the loop before you perform it.
If you think about how the loop above works the test is done after the code to be
repeated has been performed once. For our program this is exactly what we want, we
need to ask for a value before we can decide whether or not it is valid. In order to be as
flexible as possible C# gives us another form of the loop construction which allows us
to do the test first:
while (condition)
statement or block
Note that C# makes an attempt to reduce the number of keys you need to press to run
the program by leaving out the word do. (if you put the do in the compiler will take
great delight in giving you an error message - but you had already guessed that of
course!).
for loop
Often you will want to repeat something a given number of times. The loop
constructions we have given can be used to do this quite easily:
using System;
class WhileLoopInsteadOfFor
{
public static void Main ()
{
int i ;
i = 1 ;
while ( i < 11 )
{
Console.WriteLine ( "Hello mum" ) ;
i = i + 1 ;
}
}
}
Code Sample 06 While Loop instead of For
The variable which controls This useless program prints out hello mum 10 times. It does this by using a variable
things is often called the to control the loop. The variable is given an initial value (1) and then tested each
control variable, and is time we go around the loop. The control variable is then increased for each pass
usually given the name i. through the statements. Eventually it will reach 11, at which point the loop
terminates and our program stops.
C# provides a construction to allow you to set up a loop of this form all in one:
for ( setup ; finish test ; update )
{
things we want to do a given
number of times
}
We could use this to re-write the above program as:
using System;
class ForLoop
{
public static void Main ()
{
int i ;
for ( i = 1 ; i < 11 ; i = i + 1 )
{
Console.WriteLine ( "Hello mum" ) ;
}
}
}
Code Sample 07 For loop
The setup puts a value into the control variable which it will start with. The test is a
condition which must be true for the for -- loop to continue. The update is the
statement which is performed to update the control variable at the end of each loop.
Note that the three elements are separated by semicolons. The precise sequence of
events is as follows:
Writing a loop in this way is quicker and simpler than using a form of while because
it keeps all the elements of the loop in one place instead of leaving them spread about
the program. This means that you are less likely to forget to do something like give the
control variable an initial value, or update it.
If you are so stupid as to mess around with the value of the control variable in the loop
you can expect your program to do stupid things, i.e. if you put i back to 0 within the
loop it will run forever. And serve you right.
using System;
class GlazerCalc
{
static void Main()
{
double width, height, woodLength, glassArea;
const double MAX_WIDTH = 5.0 ;
const double MIN_WIDTH = 0.5 ;
const double MAX_HEIGHT = 3.0 ;
const double MIN_HEIGHT = 0.75 ;
string widthString, heightString;
do {
Console.Write ( "Give the width of the window between " +
MIN_WIDTH + " and " + MAX_WIDTH + " :" );
widthString = Console.ReadLine();
width = double.Parse(widthString);
} while ( width < MIN_WIDTH || width > MAX_WIDTH ) ;
do {
Console.Write ( "Give the height of the window between " +
MIN_HEIGHT + " and " + MAX_HEIGHT + " :" );
heightString = Console.ReadLine();
height = double.Parse(heightString);
} while ( height < MIN_HEIGHT || height > MAX_HEIGHT );
You can see examples of this construction in the for loop definition in the example
above.
The other shorthand which we use is when we add a particular value to a variable. We
could put:
house_cost = house_cost + window_cost;
This is perfectly OK, but again is rather long winded. C# has some additional operators
which allow us to shorten this to:
house_cost += window_cost;
The += operator combines addition and the assignment, so that the value in
house_cost is increased by window_cost. Some other shorthand operators are:
There are other combination operators; I will leave you to find them!
I have used the # character to get my thousands printed out with commas:
i: 150 f: 1,234.57
Note that the formatter only uses the # characters and commas that it needs. The value
150 does not have a thousands digit so it and the comma are left out. Note also though
that I have included a 0 as the smallest digit. This is so that when I print the value 0 I
actually get a value printed, otherwise when I print zero I get nothing on the page.
Printing in columns
Finally I can add a width value to the print layout information. This is very useful if
you want to print material in columns:
int i = 150 ;
double f = 1234.56789 ;
Console.WriteLine ( "i: {0,10:0} f: {1,15:0.00}", i, f ) ;
Console.WriteLine ( "i: {0,10:0} f: {1,15:0.00}", 0, 0 ) ;
This would produce the output:
i: 150 f: 1234.57
i: 0 f: 0.00
The integer value is printed in a column 10 characters wide, and the double is printed
in a 15 character wide column. At the moment the output is right justified, if I want the
numbers left justified I make the width negative:
int i = 150 ;
double f = 1234.56789 ;
Console.WriteLine ( "i: {0,-10:0} f: {1,-15:0.00}", i, f ) ;
Console.WriteLine ( "i: {0,-10:0} f: {1,-15:0.00}", 0, 0 ) ;
This would produce the output:
i: 150 f: 1234.57
i: 0 f: 0.00
Note that this justification would work even if you were printing a string rather than a
number, so if you want to print columns of words you can use this technique to do it.
You can specify the print width of any item, even a piece of text, which makes printing
in columns very easy.
3 Creating Programs
In this chapter we will build on our programming abilities to make programs that are
broken down into manageable chunks and find out how a program can store and
manipulate large amounts of data using arrays.
3.1 Methods
We have already come across the methods Main, WriteLine and ReadLine. Main is
the method we write which is where our program starts. WriteLine and ReadLine
were provided by the creators of C# to give us a way of displaying text and reading
information from the user.
This is what methods are all about. Your programs will contain methods that you create
to solve parts of the problem and they will also use methods that have been provided
by other people. In this section we are going to consider why methods are useful and
how you can create your own.
using System ;
class MethodDemo
{
static void doit ()
{
Console.WriteLine ("Hello");
}
public static void Main ()
{
doit();
doit();
}
}
Code Sample 09 Simple Method
In the main method I make two calls of doit. Each time I call the method the code in
the block which is the body of the method is executed. In this case it contains a single
statement which prints "Hello" on the console. The result of running the above
program would be:
Hello
Hello
So, we can use methods to save us from writing the same code twice. We simply put
the code inside a method body and then call it when we need it.
3.1.2 Parameters
At this point methods are useful because they let us use the same block of statements at
many points in the program. However, they become more useful if we allow them to
have parameters.
A parameter is a means of passing a value into a method call. The method is given the
data to work on. As an example, consider the code below:
using System ;
class MethodDemo
{
static void silly ( int i )
{
Console.WriteLine ( "i is : " + i ) ;
}
class ReturnDemo
{
static int sillyReturnPlus ( int i )
{
i = i + 1;
Console.WriteLine ( "i is : " + i ) ;
return i;
}
using System;
class UsefulMethod
{
static double readValue(
string prompt, // prompt for the user
double low, // lowest allowed value
double high // highest allowed value
)
{
double result = 0;
do
{
Console.WriteLine(prompt +
" between " + low +
" and " + high);
string resultString = Console.ReadLine();
result = double.Parse(resultString);
} while ((result < low) || (result > high));
return result;
}
Optional Arguments
Sometimes the value of an argument might have a sensible default value. For example,
if we just wanted the readValue to fetch a value from the user and not display a
prompt we could do this by providing an empty string:
x = readValue(low:25, high:100, prompt: "");
However, this is a bit messy. Instead we can change the definition of the method to
give a default value for the prompt parameter:
static double readValue (
double low, // lowest allowed value
double high, // highest allowed value
string prompt = "", // optional prompt for the user
)
{
...
}
We can now call the method and leave the prompt out if we like:
x = readValue(25, 100);
When the method runs the prompt will be set to an empty string if the user doesn’t
provide a value.
Note that I’ve had to rearrange the order of the parameters so that the prompt is the last
parameter. Optional parameters must be provided after all the required ones.
There is a potential problem here however. Consider this method:
int test = 20 ;
addOne(test);
Console.WriteLine ( "test is : " + test ) ;
The piece of C# above calls the method with the variable test as the argument. When
it runs it prints out the following:
i is : 21
test is : 20
It is very important that you understand what is happening here. The value of test is
being used in the call of addOne. The program works out the result of the expression to
be passed into the method call as an argument. It then passes this value into the call.
This means that you can write calls like:
test = 20 ;
addOne(test + 99);
This would print out:
i is : 120
Pass by value is very safe, because nothing the method does can affect variables in the
code which calls it. However, it is a limitation when we want to create a method which
returns more than one value.
In this case the method call has made changes to the content of the variable. Note that
C# is careful about when a parameter is a reference. You have to put the word ref in
the method heading and also in the call of the method.
do
{ string intString = readString (prompt) ;
result = int.Parse(intString);
} while ( ( result < low ) || ( result > high ) );
return result;
}
The readString method will read text and make sure that the user does not enter
empty text. The readInt method reads a number within a particular range. Note how I
have rather cleverly used my readString method in my readInt one, so that the
user can't enter an empty string when a number is required. We can use the methods as
follows:
string name;
name = readString( "Enter your name : " );
int age;
age = readInt ( "Enter your age : ", 0, 100);
I could add methods to read floating point values as well. In fact one thing I tend to do
when working on a project is create a little library of useful methods like these which I
can use.
using System;
class MethodLibraries
{
static string readString(string prompt)
{
string result;
do
{
Console.Write(prompt);
result = Console.ReadLine();
} while (result == "");
return result;
}
do
{
string intString = readString(prompt);
result = int.Parse(intString);
} while ((result < low) || (result > high));
return result;
}
int age;
age = readInt("Enter your age : ", 0, 100);
Console.WriteLine("Age: " + age);
}
}
Code Sample 13 Using Method Libraries
chunk of memory is used to hold the value and it also makes sure that we only ever use
that value correctly. The C# compiler also looks after the part of a program within
which a variable has an existence. This is called the scope of a variable.
{
int i ;
}
{
int i ;
{
int j ;
}
}
The first incarnation of i has been destroyed before the second, so this code is OK.
3.3 Arrays
We now know how to create programs that can read values in, calculate results and
print them. Our programs can also make decisions based on the values supplied by the
user and also repeat actions a given number of times.
It turns out that you now know about nearly all the language features that are required
to implement every program that has ever been written. Only one thing is missing, and
that is the ability to create programs which store large amounts of data. Arrays are one
way to do this, and we are going to find out about them next.
scores tag you reach the array box. Actually, it probably doesn't use wood or rope, but
you should get a picture of what is going on here.
A constant variable is given a value when it is declared. This value can then only be
read by the program, never updated. So, if I wanted to write a scores program that
could be easily changed for any size of team I could write:
using System;
class ArrayDemo
{
public static void Main ()
{
const int SCORE_SIZE = 1000;
int [] scores = new int [SCORE_SIZE] ;
for ( int i=0; i < SCORE_SIZE; i=i+1)
{
scores [i] = readInt ( "Score : ", 0,1000);
}
}
}
Code Sample 16 Using an Array
The variable SCORE_SIZE is an integer which has been marked with const. This
means that it cannot be changed by statements within the program. It will never have a
value other than 1000. There is a convention that constants of this kind are given in
LARGE LETTERS with an underscore between words.
Everywhere I previously used a fixed value to represent the size of the array I now use
my constant instead. This means that if the size of the team changes I just have to
change the value assigned when the constant is declared and then re-compile the
program. The other benefit of this is that the for loop now looks a lot more
meaningful. Since the value of i is now going from 0 to SCORE_SIZE it is more
obvious to the reader that it is working through the score array.
if (monthNo == 1)
monthName = "January";
if (monthNo == 2)
monthName = "February";
However this would be tedious to write. A neater way would be to use an array which
you could call monthNames. Then we could do something like this:
monthName = monthNames[monthNo];
For this to work we would have to make sure that each of the elements in the
monthNames array would hold the name of the mon.
string[] monthNames = new string[13];
So we would have to do some setting up before we use the lookup table:
monthNames[1] = "January";
monthNames[2] = "February";
the length of the array automatically if required. You can also initialise 2D arrays as
well.
int [,] squareWeights = new int [3,3]
{
{1,0,1},
{0,2,0},
{1,0,1}
};
The code above makes a 2D array that contains weighting values for a clever noughts
and crosses (tic tac toe) playing program that I might write. It represents my belief that
the centre and corner squares are the most valuable. When my program is making its
first move it will look for a square that has the highest number, and try to play there.
of a problem that has occurred. When Parse fails it creates an exception object that
describes the bad thing that has just happened (in this case input string not in the
correct format). The program above ignores the exception object and just registers to
the exception event but we can improve the diagnostics of our program by catching the
exception if we wish:
int age;
try
{
age = int.Parse(ageString);
Console.WriteLine("Thank you");
}
catch (Exception e)
{
// Get the error message out of the exception
Console.WriteLine(e.Message);
}
Code Sample 18 Using the Exception message
The catch now looks like a method call, with the Exception e being a parameter to
the method. This is exactly how it works. Within the catch clause the value of e is set
to the exception that was thrown by Parse. The Exception type has a property called
Message which contains a string describing the error. If a user types in an invalid
string the program above will write the text in the exception, which contains the
message:
Input string was not in a correct format.
This message is obtained from the exception that was thrown. This is useful if the code
inside the try block could throw several different kinds of exception, since it means
that the message reflects what has actually happened. The Exception object also
contains other properties that can be useful.
try
{
// Exceptions at this level will be caught by the
// "outer" catch clause
try
{
// Exceptions at this level will be caught by the
// "inner" catch clause
}
catch (Exception inner)
{
// This is the "inner" catch clause
}
In the above code the statements in the finally part are guaranteed to run, either
when the statements in the try part have finished, or just before execution leaves the
catch part of your program.
1 = casement
2 = standard
3 = patio door
Your program can then calculate the cost of the appropriate window by selecting type
and giving the size. Each method asks the relevant questions and works out the price of
that kind of item.
When you come to write the program you will probably end up with something like:
if ( selection == 1 )
{
handleCasement();
}
else
{
if ( selection == 2 )
{
handleStandard();
}
else
{
if ( selection == 3 )
{
handlePatio() ;
}
else
{
Console.WriteLine ( "Invalid number" );
}
}
}
This would work OK, but is rather clumsy. You have to write a large number of if
constructions to activate each option.
switch (selection)
{
case 1 :
handleCasement ();
break ;
case 2 :
handleStandard () ;
break ;
case 3 :
handlePatio () ;
break ;
default :
Console.WriteLine ( "Invalid number" ) ;
break ;
}
Code Sample 19 Using a Switch
The switch construction takes a value which it uses to decide which option to
perform. It executes the case which matches the value of the switch variable. Of
course this means that the type of the cases that you use must match the switch
selection value although, in true C# tradition, the compiler will give you an error if you
make a mistake. The break statement after the call of the relevant method is to stop
the program running on and performing the code which follows. In the same way as
you break out of a loop, when the break is reached the switch is finished and the
program continues running at the statement after the switch.
Another useful feature is the default option. This gives the switch somewhere to go
if the switch value doesn't match any of the cases available; in our case (sorry!) we put
out an appropriate message.
You can use the switch construction with types other than numbers if you wish:
switch (command)
{
case "casement" :
handleCasement ();
break ;
case "standard" :
handleStandard () ;
break ;
case "patio" :
handlePatio () ;
break ;
default :
Console.WriteLine ( "Invalid command" ) ;
break ;
}
This switch uses a string to control the selection of the cases. However, your users
would not thank you for doing this, since it means that they have to type in the
complete name of the option, and of course if they type a character wrong the
command is not recognised.
Multiple cases
You can use multiple case items so that your program can execute a particular switch
element if the command matches one of several options:
switch (command)
{
case "casement" :
case "c" :
handleCasement ();
break ;
case "standard" :
case "s" :
handleStandard () ;
break ;
case "patio" :
case "P" :
handlePatio () ;
break ;
default :
Console.WriteLine ( "Invalid command" ) ;
break ;
}
The above switch will select a particular option if the user types the full part of the
name or just the initial letter. If you want to perform selection based on strings of text
like this I’d advise you to take a look at the ToUpper and ToLower methods provided
by the string type. These can be used to obtain a version of a string which is all in
upper or lower case, which can make the testing of the commands much easier:
switch (command.ToUpper())
{
case "CASEMENT" :
case "C" :
....
C# File in
Windows
program stream
item it hasn’t seen before it will automatically look in the namespaces it has been told
to use. In other words, when the compiler sees the statement:
Console.WriteLine("Hello World");
- it knows to look in the System namespace for that object so that it can use the
WriteLine method on it. If the programmer miss-types the class name:
Consle.WriteLine("Hello World");
- the compiler will look in the System namespace, fail to find an object called
Console and generate a compilation error.
This is the same error that you will get if you try to use the StreamWriter class
without telling the compiler to look in the System.IO namespace. In other words, to
use the file handing classes you will need to add the following statement at the very top
of your program:
using System.IO;
It is possible to put one namespace inside another (just like a librarian would put a
cabinet of Vases in the Roman room which he could refer to as Roman.Vases) and so
the IO namespace is actually held within the System namespace. However, just
because you use a namespace, this does not imply that you use all the namespaces
defined within it, and so you must include the above line for file handling objects to be
available.
Namespaces are a great way to make sure that names of items that you create don’t
clash with those from other programmers. We will see how you can create your own
namespaces later on.
using System;
using System.IO;
class FileWriteDemo
{
EndOfStream that a program can use to determine when the end of the file has been
reached. When the property becomes true the end of the file has been reached.
StreamReader reader = new StreamReader("Test.txt");
while (reader.EndOfStream == false)
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
reader.Close();
The above code will open up the file test.txt and display every line in the file on the
console. The while loop will stop the program when the end of the file is reached.
using System;
using System.IO;
class FileWriteandReadDemo
{
The above statements create a string variable which contains the path to a file called
sales.txt. This file is held in the folder November, which is in turn held in the folder
2009, which is held in the folder data which is on drive C.
The backslash (\) characters in the string serve to separate the folders along the path to
the file. Note that I have specified a string literal that doesn’t contain control characters
(that is what the @ at the beginning of the literal means) as otherwise the \ characters in
the string will get interpreted by C# as the start of a control sequence. If you have
problems where your program is not finding files that you know are there, I’d advise
you to make sure that your path separators are not getting used as control characters.
4 Creating Solutions
4.1 Our Case Study: Friendly Bank
The bulk of this section is based on a case study which will allow you to see the
features of C# in a strong context. You are taking the role of a programmer who will
be using the language to create a solution for a customer.
The program we are making is for a bank, the "United Friendly and Really Nice Bank
of Lovely People ™", otherwise known as the Friendly Bank. We will be creating the
entire bank application using C# and will be exploring the features of C# that make this
easy.
It is unlikely that you will get to actually implement an entire banking system during
your professional career as a programmer (although it might be quite fun – and
probably rather lucrative). However, from a programming point of view it is an
interesting problem and as we approach it we will uncover lots of techniques which
will be useful in other programs that we might write.
Bank Notes
At the end of some sections there will be a description of how this new piece of C# will affect how we create our bank system.
These notes should put the feature into a useful context.
Sample states
Enumerated types are very useful when storing state information. States are not quite
the same as other items such as the name of a customer or the balance of their account.
For example, if I am writing a program to play the game Battleships (where squares of
the "sea" hold different types of craft which can be attacked) I may decide that a given
square of the sea can have the following thing in it:
• Empty sea
• Attacked
• Battleship
• Cruiser
• Submarine
• Rowing boat
If you think about it, I am sort of assembling more metadata here, in that I have
decided that I need to keep track of the sea and then I have worked out exactly what I
can put in it. I could do something with numbers if I like:
• Empty sea = 1
• Attacked = 2
• Battleship = 3
• Cruiser = 4
• Submarine = 5
• Rowing boat = 6
However, this would mean that I have to keep track of the values myself and remember
that if we get the value 7 in a sea location this is clearly wrong.
C# has a way in which we can create a type which has just a particular set of possible
values. These types are called "enumerated types":
enum SeaState
{
EmptySea,
Attacked,
Battleship,
Cruiser,
Submarine,
RowingBoat
} ;
I have created a type called SeaState which can be used to hold the state of a
particular part of the sea. It can only have the given values above, and must be
managed solely in terms of these named enumerations. For example I must write:
SeaState openSea ;
openSea = SeaState.EmptySea;
My variable openSea is only able to hold values which represent the state of the sea
contents. Of course C# itself will actually represent these states as particular numeric
values, but how these are managed is not a problem for me.
Note that types I create (like SeaState) will be highlighted by the editor in a blue
colour which is not quite the same as keywords.
This shows that these items are extra types I have created which can be used to create
variables, but they are not actually part of the C# language, like keywords are. It is
important that you understand what is happening here. Previously we have used types
that are part of C#, for example int and double. Now we have reached the point where
we are actually creating our own data types which can be used to hold data values that
are required by our application.
enum TrafficLight
{
Red,
RedAmber,
Green,
Amber
} ;
class EnumDemonstration
{
4.3 Structures
Structures let us organise a set of individual values into a cohesive lump which we can
map onto one of the items in the problem that we are working on. This is important in
many applications.
A sample structure
From your specification you know that the program must hold the following:
• customer name - string
• customer address - string
• account number - integer value
• account balance - integer value
• overdraft limit - integer value
The Friendly Bank have told you that they will only be putting up to 50 people into
your bank storage so, after a while you come up with the following:
const int MAX_CUST = 50;
struct Account
{
public AccountState State;
public string Name ;
public string Address ;
public int AccountNumber ;
public int Balance ;
public int Overdraft ;
} ;
This defines a structure, called Account, which contains all the required customer
information. Having done this we can now define some variables:
Account RobsAccount;
This statement creates a single Account variable which is called RobsAccount. The
program can put values into the member elements of this account.
We refer to individual members of a structure by putting their name after the struct
variable we are using with a . (full stop) separating them, for example:
RobsAccount.Name="Rob";
- would refer to the string field Name in the structured variable RobsAccount. (i.e.
the Name value in RobsAccount)
using System;
enum AccountState
{
New,
Active,
UnderAudit,
Frozen,
Closed
} ;
struct Account
{
public AccountState State;
public string Name;
public string Address;
public int AccountNumber;
public int Balance;
public int Overdraft;
} ;
class BankProgram
{
Structures get really useful when we create arrays of them. As we saw with the scoring
program, it is hard to manage individual items, but if we use an array things become
much easier.
const int MAX_CUST = 100;
Account [] Bank = new Account [MAX_CUST];
This declaration sets up an entire array of customers, called Bank which can hold all
the customers. Note that I've rather cleverly set up a variable called MAX_CUST
which is presently set at 100. This gives the maximum number of customers that our
bank can hold.
We can assign one structure variable to another, just as we would any other variable
type. When the assignment is performed all the values in the source structure are
copied into the destination:
Bank[0] = RobsAccount;
This would copy the information from the RobsAccount structure into the element at
the start of the Bank array.
You can do this with elements of an array of structures too, so that:
Bank [25].Name
- would be the string containing the name of the customer in the element with subscript
25.
information about a bank Account holder. This approach is how you attack more
complicated problems. We can get all the details of what the types should hold from
the metadata that comes from discussion with our customer.
For example, if we want to create a really impressive double glazing management
program we could come up with something like this:
enum WindowState
{
Quoted,
Ordered,
Manufactured,
Shipped,
Installed
} ;
struct Window
{
public WindowState state ;
public double Width ;
public double Height ;
public string Description ;
} ;
This would hold information about a particular window in a house, including the
dimensions of the window, the state of the window order and a string describing the
window itself. For a particular house, which contains a number of windows, we could
create an array of Window structures.
• objects don’t add any new behaviours to our programs – we know just about
everything we need to know to write programs when we have learnt about
statements, loops, conditions and arrays.
• objects are best regarded as a solution to the problem of design. They let us
talk about systems in general terms. We can go back and refine how the
objects actually do their tasks later.
You can write just about every program that has ever been written just by using the
technologies that we have so far looked at. But objects allow us to work in a much
nicer way. And so we are going to have to get the hang of them, like it or not…
class StructsAndObjectsDemo
{
public static void Main ()
{
AccountStruct RobsAccountStruct ;
RobsAccountStruct.Name = "Rob";
Console.WriteLine ( RobsAccountStruct.Name );
}
}
Code Sample 26 Simple Account Stucture
This implements a very simple bank account, where we are only holding the name of
the account holder. The Main method creates a structure variable called
RobsAccountStruct.
RobsAccountStruct
Name: Rob
It then sets the name property of the variable to the string "Rob". If we run this
program it does exactly what you would expect, in that it prints out the name "Rob". If
the structure contained other items about the bank account these would be stored in the
structure as well, and I could use them in just the same way.
class Account
{
public string Name ;
} ;
class StructsAndObjectsDemo
{
public static void Main ()
{
Account RobsAccount ;
RobsAccount.Name = "Rob";
Console.WriteLine (RobsAccount.Name );
}
}
Code Sample 27 Non-compiling Account class
The account information is now being held in a class, rather than a structure. The
account class is called, quite simply, Account. The problem is that when we compile
the program we get this:
ObjectDemo.cs(12,3): error CS0165: Use of unassigned local variable
' RobsAccount'
So, what is going on? To understand what is happening you need to know what is
performed by the line:
Account RobsAccount;
This looks like a declaration of a variable called RobsAccount. But in the case of
objects, this is not what it seems.
RobsAccount
What you actually get when the program obeys that line is the creation of a reference
called RobsAccount. Such references are allowed to refer to instances of the
Account. You can think of them as a bit like a luggage tag, in that they can be tied to
something with a piece of rope. If you have the tag you can then follow the rope to the
object it is tied to.
But when we create a reference we don't actually get one of the things that it refers to.
The compiler knows this, and so it gives me an error because the line:
RobsAccount.Name = "Rob";
- is an attempt to find the thing that is tied to this tag and set the name property to
"Rob". Since the tag is presently not tied to anything our program would fail at this
point. The compiler therefore says, in effect, "you are trying to follow a reference
which does not refer to anything, therefore I am going to give you a 'variable
undefined' error".
We solve the problem by creating an instance of the class and then connecting our tag
to it. This is achieved by adding a line to our program:
class Account
{
public string Name ;
} ;
class StructsAndObjectsDemo
{
public static void Main ()
{
Account RobsAccount ;
RobsAccount = new Account();
RobsAccount.Name = "Rob";
Console.WriteLine (RobsAccount.Name );
}
}
Code Sample 28 Compiling Account Class
The line I have added creates a new Account object and sets the reference
RobsAccount to refer to it.
Account
RobsAccount
Name: Rob
We have seen this keyword new before. We use it to create arrays. This is because an
array is actually implemented as an object, and so we use new to create it. The thing
that new creates is an object. An object is an instance of a class. I'll repeat that in a
posh font:
4.4.2 References
We now have to get used to the idea that if we want to use objects, we have to use
references. The two come hand in hand and are inseparable. Structures are kind of
useful, but for real object oriented satisfaction you have to have an object, and that
means that we must manage our access to a particular object by making use of
references to it. Actually this is not that painful in reality, in that you can treat a
reference as if it really was the object just about all of the time, but you must remember
that when you hold a reference you do not hold an instance, you hold a tag which is
tied onto an instance…
Account RobsAccount ;
RobsAccount = new Account();
RobsAccount.Name = "Rob";
Console.WriteLine (RobsAccount.Name );
Account Temp ;
Temp = RobsAccount;
Temp.Name = "Jim";
Console.WriteLine (RobsAccount.Name );
Code Sample 29 Multiple References
The question is; what would the second call of WriteLine print out? If we draw a
diagram the answer becomes clearer:
Account
RobsAccount
Name: Jim
Temp
Both of the tags refer to the same instance of Account. This means that any changes
which are made to the object that Temp refers to will also be reflected in the one that
RobsAccount refers to, because they are the same object. This means that the
program would print out Jim, since that is the name in the object that RobsAccount is
referring to.
This indicates a trickiness with objects and references. There is no limit to the number
of references that can be attached to a single instance, so you need to remember that
changing the object that a reference refers to may well change that instance from the
point of view of other objects.
No References to an Instance
Just to complete the confusion we need to consider what happens if an object has no
references to it:
Account RobsAccount ;
RobsAccount = new Account();
RobsAccount.Name = "Rob";
Console.WriteLine (RobsAccount.Name );
RobsAccount = new Account();
RobsAccount.Name = "Jim";
Console.WriteLine (RobsAccount.Name );
Code Sample 30 No references to an instance
This code makes an account instance, sets the name property of it to Rob and then
makes another account instance. The reference RobsAccount is made to refer to the
new item, which has the name set to Jim. The question is: What happens to the first
instance? Again, this can be made clearer with a diagram:
Account
RobsAccount
Name: Rob
Account
Name: Jim
The first instance is shown “hanging” in space, with nothing referring to it. As far as
making use of data in the instance is concerned, it might as well not be there. Indeed
the C# language implementation has a special process, called the “Garbage Collector”
which is given the job of finding such useless items and disposing of them. Note that
the compiler will not stop us from “letting go” of items like this.
You should also remember that you can get a similar effect when a reference to an
instance goes out of scope:
{
Account localVar ;
localVar = new Account();
}
The variable localVar is local to the block. This means that when the program
execution leaves the block the local variable is discarded. This means that the only
reference to the account is also removed, meaning another job for the garbage
collector.
I go up to the one above that (which must be the next lightest). Then I go down the
dark side (Luke) and repeat the process. The neat thing about this approach is also that
adding new items is very easy; I just find the place on the tree that they need to be hung
on and attach the reference there.
Searching is also very quick, in that I can look at each node and decide which way to
look next until I either find what I am looking for or I find there is no reference in the
required direction, in which case the item is not in the structure.
Reference Importance
The key to this way of working is that an object can contain references to other objects,
as well as the data payload. We will consider this aspect of object use later; for now we
just need to remember that the reference and the object are distinct and separate.
“And so, my fellow Americans: ask not what your country can do for you—ask what
you can do for your country” (huge cheers)
We don’t do things to the bank account. Instead we ask it to do these things for us. The
design of our banking application can be thought of in terms of identifying the objects
that we are going to use to represent the information and then specifying what things
they should be able to do. The really clever bit is that once we have decided what the
bank account should do, we then might be able to get somebody else to make it do
these things.
If our specification is correct and they implement it properly, we don’t have to worry
precisely how they made it work – we just have to sit back and take the credit for a job
well done.
This brings us back to a couple of recurring themes in this document; metadata and
testing. What a bank account object should be able to do is part of the metadata for this
object. And once we have decided on the actions that the account must perform, the
next thing we need to do is devise a way in which each of the actions can be tested.
In this section we are going to implement an object which has some of the behaviours
of a proper bank account.
- and take away all my money. If we are going to provide a way of stopping this from
happening we need to protect the data inside our objects.
class Bank
{
public static void Main ()
{
Account RobsAccount;
RobsAccount = new Account();
if ( RobsAccount.WithdrawFunds (5) )
{
Console.WriteLine ( "Cash Withdrawn" ) ;
}
else
{
Console.WriteLine ( "Insufficient Funds" ) ;
}
}
}
public Methods
You may have noticed that I made the WithdrawFunds method public. This means
that code running outside the class can make calls to that method. This has got to be the
case, since we want people to interact with our objects by calling methods in them. In
general the rules are:
• if it is a data member (i.e. it holds data) of the class, make it private
• if it is a method member (i.e. it does something) make it public
Of course, the rules can be broken on special occasions. If you don’t care about
possible corruption of the member and you want your program to run as quickly as
possible you can make a data member public. If you want to write a method which is
only used inside a class and performs some special, secret, task you can make it
private.
Programmer’s Point: Use coding conventions to show which things are private
If you look closely at the code I write (and I would advise you to do this, it’s good stuff) you will find that when I
write the name of a public item I use a capital letter to start the name (as in the case of WithdrawFunds to
withdraw from our bank account). But I make the first letter of private members lower case (as in the case of the
balance data member of our bank account). This makes it easy for someone reading my code, because they can see
from the name of a class member whether or not it is public or private. The convention also extends to variables
which are local to a block. These (for example the ubiquitous i) always start with a lower case letter.
Some people go further and do things like put the characters m_ in front of variables which are members of a class.
They would call their balance value m_balance so that class members are easy to spot. I don’t usually go that far,
because I reckon that the name of the member is usually enough, but opinions differ on this one. The most
important thing in this situation is that the whole programming team adopts the same conventions on matters
like these. In fact, most development companies have documents that set out the coding conventions they use, and
expect developers to adhere to these.
which is tedious. Later we will consider the use of unit tests which make this much
easier.
Now I can create accounts and set balances and interest rates on them. (of course if I
was doing this properly I'd make this stuff private and provide methods etc, but I'm
keeping things simple just now).
Account RobsAccount = new Account();
RobsAccount.Balance = 100;
RobsAccount.InterestRateCharged = 10;
The snag is; I've been told that the interest rate is held for all the accounts. If the
interest rate changes it must change for all accounts. This means that to implement the
change I'd have to go through all the accounts and update the rate. This would be
tedious, and if I missed one account, possibly expensive.
I solve the problem by making the interest rate member static:
public class Account
{
public decimal Balance ;
public static decimal InterestRateCharged ;
}
The interest rate is now part of the class, not part of any instance. This means that I
have to change the way that I get hold of it:
Account RobsAccount = new Account();
RobsAccount.Balance = 100;
Account.InterestRateCharged = 10;
Since it is a member of the class I now have to use the class name to get hold of it
instead of the name of the instance reference.
“But wait a minute”, you say, “We’ve been making objects for a while and I’ve never
had to provide a constructor method”. This is because the C# compiler is, for a change,
being friendly here. Rather than shout at you for not providing a constructor method,
the compiler instead quietly creates a default one for you and uses that.
You might think this is strange, in that normally the compiler loses no time in telling
you off when you don’t do something, but in this case it is simply solving the problem
without telling you. There are two ways to look at this:
nice compiler: the compiler is trying to make life easier for you
evil compiler: the compiler knows that if it does this automatically now you will
suffer more later when you try to understand why you don’t need to add one
How you regard the action of the compiler is up to you.
This could create a new account and set the name property to Rob Miles, the address
to Hull and the initial balance to zero. It turns out that I can do this very easily, all I
have to do is make the constructor method to accept these parameters and use them to
set up the members of the class:
class Account
{
// private member data
private string name;
private string address;
private decimal balance;
// constructor
public Account (string inName, string inAddress,
decimal inBalance)
{
name = inName;
address = inAddress;
balance = inBalance;
}
}
The constructor takes the values supplied in the parameters and uses them to set up the
members of the Account instance that is being created. In this respect it behaves
exactly as any other method call.
class Bank
{
public static void Main()
{
Account robsAccount;
robsAccount = new Account("Rob", "Robs House",
1000000);
}
}
Code Sample 34 Using a custom constructor
The code above would create an account for Rob which has 1000000 pounds in it. I
wish.
Note that adding a constructor like this has one very powerful ramification:
You must use the new constructor to make an instance of a class, i.e. the only way I
can now make an Account object is by supplying a name, address and starting
balance. If I try to do this:
robsAccount = new Account();
- the compiler will stop being nice to me and produce the error:
AccountTest.cs(9,27): error CS1501: No overload for method
'Account' takes '0' arguments
What the compiler is telling me is that there is no constructor in the class which does
not have any parameters. In other words, the compiler only provides a default
constructor if the programmer doesn't provide a constructor.
This can cause confusion if we have made use of the default constructor in our program
and we then add one of our own. The default constructor is no longer supplied by the
compiler and our program now fails to compile correctly. In that situation you have to
either find all the calls to the default one and update them, or create a default
constructor of your own for these calls to use. Of course you don't have to do this
because your design of the program was so good that you never have this problem. Just
like me, hem hem.
above, since the call of this does all the work, the body of the constructor can be
empty.
class Bank
{
public static void Main()
{
const int MAX_CUST = 100;
Account[] Accounts = new Account[MAX_CUST];
Accounts[0] = new Account("Rob", "Robs House",
1000000);
Accounts[1] = new Account("Jim", "Jims House");
Accounts[2] = new Account("Fred");
}
}
Code Sample 35 Overloaded Constructors
The sample code above shows constructor overloading being used properly. The code
creates an array of Account references (called Accounts) and then sets the first three
elements to point to Account instances. The first element points to an Account for Rob
with a full address and 1000000 pounds. The second element (element 1) refers to an
account for Jim with his address and the default balance of 0. The third element
(element 0) refers to an account for Fred which has the default address ("Not
Supplied") and a default balance of 0.
This poses a problem. It looks as if we can veto stupid values at every point except the
one which is most important, i.e. when the object is first created.
if (SetBalance(inBalance)==false)
errorMessage = errorMessage + "Bad Balance: " +
inBalance;
if (SetName(inName) == false)
{
errorMessage = errorMessage + "Bad name: " + inName;
}
if (SetAddress(inAddress) == false)
{
errorMessage = errorMessage + " Bad addr: " +
inAddress;
}
if (errorMessage != "")
{
throw new Exception("Account construction failed "
+ errorMessage);
}
}
Code Sample 36 Constructor Failing
This version of the constructor assembles an error message which describes everything
which is wrong with the account. Each new thing which is wrong is added to the
message and then the whole thing is put into an exception and thrown back to the
caller.
about the C# interface mechanism with a long description of how windows and buttons
work. This will earn you zero marks.
bank, this means that we want to deal with objects in terms of IAccount,(the set of
account abilities) rather than CustomerAccount (a particular account class).
In C# terms this means that we need to be able to create reference variables which refer
to objects in terms of interfaces they implement, rather than the particular type that
they are. It turns out that this is quite easy:
IAccount account = new CustomerAccount();
account.PayInFunds(50);
Console.WriteLine("Balance: " + account.GetBalance());
Code Sample 37 Simple Interface
The account variable is allowed to refer to objects which implement the IAccount
interface. The compiler will check to make sure that CustomerAccount does this, and
if it does, the compilation is successful.
Note that there will never be an instance of IAccount interface. It is simply a way that
we can refer to something which has that ability (i.e. contains the required methods).
This is the same in real life. There is no such physical thing as a "lecturer", merely a
large number of people who can be referred to as having that particular ability or role.
This means that we can create components that are used in the same way, but have
different behaviours which are appropriate to the type of item they are representing.
class Bank
{
const int MAX_CUST = 100;
if (accounts[0].WithdrawFunds(20))
{
Console.WriteLine("Withdraw OK");
}
if (accounts[1].WithdrawFunds(20))
{
Console.WriteLine("Withdraw OK");
}
}
}
Code Sample 38 Using Components
The code above shows how this would really be used. The accounts array can hold
references to any object that implements the IAccount interface. This includes
CustomerAccount and BabyAccount objects. The first element in the array (element 0)
is assigned to a CustomerAccount object and the second element (element 1) assigned
to a BabyAccount. When methods are called on these objects the one in the particular
type is used. This means that the final call of WithDrawFunds will fail because,
although the baby has enough money in the bank they are not allowed to draw out
more than 10 pounds.
From the point of view of interface design this means that the account number will be
set when the account is created and the account class will provide a method to let us get
the value (but there will not be a method to set the account number).
We don't care what the method GetAccountNumber actually does, as long as it
always returns the value for a particular account. So this requirement ends up being
expressed in the interface that is implemented by the account class.
interface IAccount
{
int GetAccountNumber ();
}
This method returns the integer which is the account number for this instance. By
placing it in the interface we can say that the account must deliver this value, but we
have not actually described how this should be done. The design of the interfaces in a
system is just this. They state that we have a need for behaviours, but they do not
necessarily state how they are made to work. I have to add comments to give more
detail about what the method does.
The need for things like account numbers, which really need to be unique in the world,
has resulted in the creation of a set of methods in the C# libraries to create things called
Globally Unique Identifiers or GUIDs. These are data items which are created based on
the date, time and certain information about the host computer. Each GUID is unique
in the world. We could use these in our Account constructor to create a GUID which
allows each account to have a unique number.
4.9 Inheritance
Inheritance is another way we can implement creative laziness. It is a way that we can
pick up behaviours from classes and just modify the bits we need to make new ones. In
this respect you can regard it as a mechanism for what is called code reuse. It can also
be used at the design stage of a program if you have a set of related objects that you
wish to create.
Inheritance lets a class pick up behaviours from the class which is its parent. You can
regard an interface as a statement by a class that it has a set of behaviours because it
implements a given interface. If a class is descended from a particular parent class this
means that it has a set of behaviours because it has inherited them from its parent. In
short:
Interface: "I can do these things because I have told you I can"
Inheritance: "I can do these things because my parent can"
The call of PayInFunds will use the method in the parent (since that has not been
overridden) but the call of WithdrawFunds will use the method in BabyAccount.
Virtual Methods
Actually, there is one other thing that we need to do in order for the overriding to work.
The C# compiler needs to know if a method is going to be overridden. This is because
it must call an overridden method in a slightly different way from a "normal" one. In
other words, the above code won't compile properly because the compiler has not been
told that WithDrawFunds might be overridden in classes which are children of the
parent class.
To make the overriding work correctly I have to change my declaration of the method
in the CustomerAccount class.
public class CustomerAccount : IAccount
{
}
The keyword virtual means “I might want to make another version of this method in
a child class”. You don’t have to override the method, but if you don’t have the word
present, you definitely can’t.
This makes override and virtual a kind of matched pair. You use virtual to
mark a method as able to be overridden and override to actually provide a
replacement for the method.
.....
}
I’m not terribly happy about doing this, the balance is very important to me and I’d
rather that nobody outside the CustomerAccount class could see it. However, for
now making this change will make the program work. Later we will see better ways to
manage this situation.
IAccount[] accounts = new IAccount[MAX_CUST];
if (accounts[0].WithdrawFunds(20))
{
Console.WriteLine("Withdraw OK");
}
if (accounts[1].WithdrawFunds(20))
{
Console.WriteLine("Withdraw OK");
}
Code Sample 39 Using Inheritance
The code above shows how we can create and use different types of account, with the
BabyAccount based on the parent CustomerAccount type. If you are having a sense of
deja vu here, it is because this is exactly the same code as we saw in the previous
sample. Code that uses these objects will work in exactly the same way as it always
did, except that the objects themselves work in a slightly different way, making the
program smaller (which we don't particularly care about) and much easier to debug
(because a fault in any of the shared methods only has to be fixed once).
Constructor Chaining
When considering constructors and class hierarchies you must remember that to create
an instance of a child class an instance of the parent must first be created. This means
that a constructor in the parent must run before the constructor in the child. In other
words, to create a BabyAccount you must first create a CustomerAccount. The
result of this is that programmers must take care of the issue of constructor chaining.
They must make sure that at each level in the creation process a constructor is called to
set up the class at that level.
This illustrates an issue that you can have with class hierarchies. They can be regarded
as "brittle" in that they are easily broken. Changes in one part of the class hierarchy can
result in you having to make changes in other parts. In the case above we had a neat
idea to improve the creating of BabyAccount instances that ended up needing changes
to the CustomerAccount class too.
This code repays careful study. Note how I have moved all the things that all accounts
must do into the parent Account class. Then I have added customised methods into the
child classes where appropriate. Note also though that I have left the interface in place.
That is because; even though I now have this abstract structure I still want to think of
the account objects in terms of their “accountness” rather than any particular specific
type.
If we make any new kinds of account classes which are based on the Account parent
each new class must provide its own version of the RudeLetterString method.
For the purpose of this part of the notes, the first point is the one which has the most
importance here. It means that all classes that are made have a number of behaviours
that they inherit from their ultimate parent, the object. If you look inside the actual
code that makes an object work you will find a method called ToString. The object
implementation of ToString returns a string description of the type of that object.
The method above is from a ChildAccount class. This class extends the
CustomerAccount and holds the name of the child's parent. The code above uses the
ToString method in the parent object and then tacks the name of the parent on the
end before returning it. The nice thing about this is that if the behaviour of the parent
class changes, i.e. new members are added or the format of the string changes, the
ChildAccount class does not have to change, since it will just make use of the
upgraded method.
if ( spaceshipPosition == missilePosition )
{
Console.WriteLine("Bang");
}
Note that I've made the x and y members of the Point class public. This is because
I'm not that concerned about protecting them, but I do want my program to run quickly.
The problem is that the above program code does not work. Even though I have put the
spaceship and the missile at the same place on the screen the word Bang is not printed.
This is because although the two Point objects hold the same data, they are not
located at the same address in memory, which means that the equals test will fail.
this.account.SetName("Rob");
This means "I have a member variable in this class called account. Call the SetName
method on that member to set the name to 'Rob'".
The ToUpper method returns a version of the string with all the letters converted to
UPPER CASE. No other characters in the string are changed. There is a corresponding
ToLower method as well.
4.12 Properties
Properties are useful. They are a bit like the switch keyword, which lets us select
things easily. We don't need properties, but C# provides them because they make
programs slightly easier to write and simpler to read.
interface IStaff
{
int Age
{
get;
set;
}
}
This is an interface that specifies that classes which implement it must contain an Age
property with both get and set behaviours.
Delegates are useful because they let us manipulate references to methods. We can
manage which particular method is going to be called in a given situation in terms of a
lump of data which we can move around.
Delegates are an important part of how events are managed in a C# program. Events
are things that happen which our program may need to respond to. They include stuff
like people pressing buttons in our user interface, clocks going tick and messages
arriving via the network. In each case we need to tell the system what to do when the
event occurs. The way that C# does this is by allowing us to create instances of
delegate classes which we give the event generators. When the event occurs (this is
sometimes called the event "firing") the method referred to by the event is called to
deliver the message. I call a delegate “A way of telling a piece of program what to do
when something happens”. A posh description would have the form:
Using a Delegate
As an example, consider the calculation of fees in our bank. The bank will have a
number of different methods which do this, depending on the type of customer and the
status of that customer. It might want to have a way in which a program can choose
which fee calculation method to use as it runs.
We have seen that things like overriding let us create methods which are specific to a
particular type of object, for example we provided a custom WithdrawFunds for the
BabyAccount class which only lets us draw out a limited amount of cash. These
techniques are very useful, but they are hard wired into the code that I write. Once I've
compiled the class the methods in it cannot change.
A delegate is a "stand in" for a method. If you call the delegate it calls the method it
presently refers to. This means I can use it as a kind of method selector. A delegate
type is created like this:
public delegate decimal CalculateFee (decimal balance);
Note that I've not created any delegates yet, I've just told the compiler what the
delegate type CalculateFee looks like. This delegate can stand in for a method
which accepts a single decimal parameter (the balance on the account) and returns a
decimal value (the amount we are going to charge the customer). An example of a
method we might want to use with this delegate you could consider is this one:
using System;
accounts
Name : "Rob"
Balance : 0
The diagram shows the state of the accounts array after we have stored our first
account. The light coloured elements are set to null. The element at the start of the
array contains a reference to the account instance.
The method to add an account to our bank has to find the first empty location in the
array and set this to refer to the account that has been added:
public bool StoreAccount (IAccount account)
{
int position = 0;
for (position = 0; position<accounts.Length; position++)
{
if (accounts[position] == null)
{
accounts[position] = account;
return true;
}
}
return false;
}
This method works through the array looking for an element containing null. If it finds
one it sets this to refer to the account it has been asked to store and then returns true.
If it does not find a null element before it reaches the end of the array it returns
false to indicate that the store has failed.
When we want to work on an account we must first find it. The bank interface provides
a method called FindAccount which will find the account which matches a particular
customer name:
IAccount fetchedAccount = arrayBank.FindAccount("Rob");
This will either return the account with the required name, or null if the account
cannot be found. In the array based implementation of the bank this is achieved by
means of a simple search:
public IAccount FindAccount ( string name )
{
int position=0 ;
for (position=0 ; position<accounts.Length ; position++)
{
if ( accounts[position] == null )
{
continue;
}
if ( accounts[position].GetName() == name )
{
return accounts[position];
}
}
return null;
}
This code works its way through the accounts array looking for an entry with a name
which matches the one being looked for. If it finds an element which contains a null
reference it skips past that onto the next one. If it reaches the end of the array without
finding a match it returns null, otherwise it returns a reference to the account that it
found.
class BankProgram
{
if(ourBank.StoreAccount(newAccount) == true)
Console.WriteLine("Account added to bank");
}
}
Code Sample 46 Storing accounts in an array
The sample code above shows how this would be used. It creates an ArrayBank that
can hold 100 accounts. It then creates a new account and stores it in the bank. It then
searches for that account by name and finds it.
In short, the hash function gives us a starting point for our search, rather than always
looking from the beginning of the array in our simple array based code above. This
greatly speeds up access to the data.
5 Advanced Programming
5.1 Generics and Collections
Generics are very useful. This statement probably doesn't tell you much about them or
what they do, but it does indicate that they are very useful. They sound a bit scary;
telling people you learned about "generics" probably conjures up images of people with
white coats and test tubes, at least amongst those who can't spell very well. But I
digress. I think the root of Generics is probably "general", in that the idea of them is
that you specify a general purpose operation and then apply it in different contexts in a
way appropriate to each of them. If this sounds a bit like abstraction and inheritance
you are sort of on the right track. If it doesn't, then it might be worth re-reading those
bits of the book until they make sense.
Perhaps the best way to talk about generics is to see how they can help us solve a
problem for the bank. We have just seen that we can store Account references in an
Array. But we know that when an array is created the programmer must specify exactly
how many elements it contains. This leads to a "straw that breaks the camel's back"
problem, where adding the 10,001st customer to the bank is not actually a cause for
celebration, because the array size was set at 10,000 and our program crashes.
One way to solve this problem is to use a really big array, but we aren't that keen on
that because it means that for smaller banks the program might be wasting a lot of
memory. Fortunately the C# libraries provide a number of solutions, starting with the
simple ArrayList.
Creating an ArrayList
It is very easy to create an ArrayList:
ArrayList store = new ArrayList();
Note that you don't have to set the size of the ArrayList, although there are
overloaded constructors that let you give this information and help the library code
along a bit:
ArrayList storeFifty = new ArrayList(50);
The ArrayList called storeFifty is initially able to store 50 references, but it can
hold more or less as required.
that the bank has many lists of customers. It will have a list of all the customers, along
with a list of "special" customers and perhaps another list of those who owe it the most
money. So, an item "in" an arraylist is never actually in it, the list actually contains a
reference to that item. When an item is removed from an arraylist, it is not necessarily
destroyed; it is just no longer on that list.
accountDictionary.Add(account.GetName(), account);
return true;
}
}
Code Sample 48 A dictionary bank
The code above shows how we can create FindAccount and StoreAccount methods
using a dictionary. The methods check to make sure that the dictionary is used
properly.
The Dictionary class is simply wonderful for storing keys and values in a typesafe
manner, and I recommend it strongly to you.
try
{
textIn = new System.IO.StreamReader(filename);
string nameText = textIn.ReadLine();
string balanceText = textIn.ReadLine();
decimal balance = decimal.Parse(balanceText);
result = new CustomerAccount(nameText,balance);
}
catch
{
return null;
}
finally
{
if (textIn != null) textIn.Close() ;
}
return result;
}
This method opens a file, fetches the balance value and then creates a new
CustomerAccount with the balance value and name.
class SaveDemo
{
public static void Main()
{
CustomerAccount test = new CustomerAccount("Rob",
1000000);
test.Save("Test.txt");
Using streams
A better solution is to give the file save method a stream to save itself, rather than a
filename. A stream is the thing that the C# library creates when we open a connection
to a file:
System.IO.TextWriter textOut =
new System.IO.StreamWriter( "Test.txt" );
The reference textOut refers to a stream which is connected to the file Test.txt. We
can create a save method which accepts the stream reference as a parameter instead of
a filename:
public void Save(System.IO.TextWriter textOut)
{
textOut.WriteLine(name);
textOut.WriteLine(balance);
}
This save method can be called from our original file save method:
public bool Save ( string filename )
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
This method creates a stream and then passes it to the save method to save the item.
Note that this is an example of overloading in that we have two methods which share
the same name.
The load method for our bank account can be replaced by one which works in a similar
way.
public static CustomerAccount Load(
System.IO.TextReader textIn)
{
CustomerAccount result = null;
try
{
string name = textIn.ReadLine();
string balanceText = textIn.ReadLine();
decimal balance = decimal.Parse(balanceText);
result = new CustomerAccount(name, balance);
}
catch
{
return null;
}
return result;
}
This method is supplied with a text stream. It reads the name and the balance from this
stream and creates a new CustomerAccount based on this data.
class BankProgram
{
public static void Main()
{
DictionaryBank ourBank = new DictionaryBank();
if (ourBank.StoreAccount(newAccount) == true)
Console.WriteLine("Account added to bank");
ourBank.Save("Test.txt");
DictionaryBank loadBank =
DictionaryBank.Load("Test.txt");
Health Warning
This is complicated stuff. I don't expect you to understand this at first reading. The
reason that it is here is for completeness. Having told you all about class hierarchies
and how useful it is to be able to base a new class on an existing one (as we did with
BabyAccount) it would be most unfair of me to leave you guessing as to how these
things can be stored and retrieved. This material is provided to give you an idea of
how you really could make a working bank, but it assumes a very good understanding
of class hierarchies, method overriding/overloading and constructor chaining.
The good news is that when you do understand this stuff you really can call yourself a
fully-fledged C# programmer.
public BabyAccount(
string newName,
decimal initialBalance,
string inParentName)
: base(newName, initialBalance)
{
parentName = inParentName;
}
}
This is a complete BabyAccount implementation. It contains an additional property,
parentName, and overrides the WithdrawFunds method to provide the new
behaviour. Note that I have created a constructor which is supplied with the name of
the account holder, the starting balance and the name of the parent. This makes use of
the constructor in the parent to set the balance and name, and then sets the parent name.
I can create a BabyAccount as follows:
BabyAccount babyJane = new BabyAccount ("Jane", 20, "John");
This would create a new BabyAccount instance and set the reference babyJane to
refer to it.
try
{
string name = textIn.ReadLine();
string balanceText = textIn.ReadLine();
decimal balance = decimal.Parse(balanceText);
string parent = textIn.ReadLine();
result = new BabyAccount (name, balance, parent);
}
catch
{
return null;
}
return result;
}
However, I'm not particularly keen on this approach. This method breaks one of the
rules of good design, in that we now have a dependency between the two classes which
means that when I change the CustomerAccount class (perhaps to add a new field
called customerPIN) I also have to update the Load method in the BabyAccount
class to make sure that this extra data is loaded. If I forget to do this the program will
compile, but when it runs it will not work correctly.
What we really want to do is make the CustomerAccount responsible for loading its
data and the BabyAccount just look after its content; in a similar way to the way the
save method uses the base keyword to save the parent object.
The way to do this is to go back to the construction process. We know that a
constructor is a method which gets control when an instance of a class is being created.
A constructor can be used to set up the data in the instance, and it can be passed
information to allow it to do this. In the code above there is a constructor for the
BabyAccount class which accepts the three data items that the BabyAccount holds
and then sets the instance up with these values.
What we do is create constructors for the CustomerAccount and BabyAccount
classes which read their information from a stream that is supplied to them:
public CustomerAccount(System.IO.TextReader textIn)
{
name = textIn.ReadLine();
string balanceText = textIn.ReadLine();
balance = decimal.Parse(balanceText);
}
This constructor sets up the new CustomerAccount instance by reading the values
from the stream that it is supplied with. I can therefore write code like this:
System.IO.TextReader textIn =
new System.IO.StreamReader(filename);
result = new CustomerAccount(textIn);
textIn.Close();
This creates a new CustomerAccount from the stream. Now I can create a
constructor for the BabyAccount which uses the constructor of the parent class:
public BabyAccount(System.IO.TextReader textIn) :
base (textIn)
{
parentName = textIn.ReadLine();
}
This removes the dependency relationship completely. If the behaviour of the
CustomerAccount constructor changes we do not have to change the BabyAccount
at all.
Note that these constructors do not do any error checking, they just throw exceptions if
something goes wrong. Bearing in mind that the only way that a constructor can fail is
to throw an exception anyway, this is reasonable behaviour.
class AccountFactory
{
public static IAccount MakeAccount(
string name, System.IO.TextReader textIn)
{
switch (name)
{
case "CustomerAccount":
return new CustomerAccount(textIn);
case "BabyAccount":
return new BabyAccount(textIn);
default:
return null;
}
}
}
This class only contains a single method, which is static. The method is given two
parameters, the name of the class to be created and a stream to read from. It uses the
name to decide which item to make, creates one, and then returns that to the caller. If
the name is not recognized it returns null. The bank load method can use this factory
to create instances of accounts as they are loaded:
public static HashBank Load(System.IO.TextReader textIn)
{
HashBank result = new HashBank();
string countString = textIn.ReadLine();
int count = int.Parse(countString);
class BankProgram
{
public static void Main()
{
DictionaryBank ourBank = new DictionaryBank();
if (ourBank.StoreAccount(newAccount))
Console.WriteLine("CustomerAccount added to bank");
if (ourBank.StoreAccount(newBabyAccount))
Console.WriteLine("BabyAccount added to bank");
ourBank.Save("Test.txt");
DictionaryBank loadBank =
DictionaryBank.Load("Test.txt");
Factory Dependencies
Note that we now have a genuine dependency between our system and the factory
class. If we ever add a new type of account we need to update the behaviour of the
factory so that it contains a case to deal with the new account type. There is in fact a
way of removing the need to do this. It involves writing code which will search for C#
classes which implement particular interfaces and creating them automatically.
However this kind of stuff is beyond the scope of this text.
this.name = inName.Trim();
return true;
}
The name is stored as a private member of the account class. The programmer has
provided three methods which let the users of my Account class deal with names.
There is a method to get the name, another to set it and another to validate it. The
validate method is called by the set method so that my business object makes sure that
an account never has an invalid name. The validate method will reject a name string
which is empty, or just contains spaces. It trims off all the spaces before and after the
name text and then checks to see if the length of the resulting string is empty. If it is,
the string is rejected.
I provide the validate method so that users of my class can check their names to make
sure that they are valid. This does not involve me in much extra work, since I also use
the method myself when I validate the name. The validate method returns a string
which gives an error message if the string is rejected. There may be several reasons
why a name is not valid, at the moment I've just given two. The reasons why a name is
invalid are of course part of the metadata for the project. I’ve also made this method
static so that names can be validated without needing to have an actual instance of
the account.
int errorCount=0;
string reply;
reply = CustomerAccount.ValidateName(null);
if (reply != "Name parameter null")
{
Console.WriteLine("Null name test failed");
errorCount++;
}
reply = CustomerAccount.ValidateName("");
if (reply != "No text in the name")
{
Console.WriteLine("Empty name test failed");
errorCount++;
}
reply = CustomerAccount.ValidateName(" ");
if (reply != "No text in the name")
{
Console.WriteLine("Blank string name test failed");
errorCount++;
}
CustomerAccount a = new CustomerAccount("Rob", 50);
if (!a.SetName("Jim"))
{
Console.WriteLine("Jim SetName failed");
errorCount++;
}
if ( a.GetName() != "Jim" ) {
Console.WriteLine("Jim GetName failed");
errorCount++;
}
if (!a.SetName(" Pete "))
{
Console.WriteLine("Pete trim SetName failed");
errorCount++;
}
if ( a.GetName() != "Pete" )
{
Console.WriteLine("Pete GetName failed");
errorCount++;
}
if (errorCount > 0 )
{
SoundSiren();
}
Code Sample 52 Testing the name setting
These are all the tests I could think of. First I test ValidateName to make sure that it
rejects both kinds of empty string. Then I make sure that I can set the name on an
account. Finally I check that the space trimming for the names works correctly.
if ( reply.Length == 0 )
{
break;
}
Console.WriteLine( "Invalid name : " + reply );
}
account.SetName(newName);
This code will perform the name editing for an account instance referred to by
account. It will read a new name in. If the name is valid the loop is broken and the
name is set. If the name is not valid the message is printed and the loop repeats. This is
not the most elegant solution, but it does keep the user informed of what it is doing and
it does work. Now that we have our edit code we need to put it somewhere.
if ( reply.Length == 0 )
{
break;
}
Console.WriteLine( "Invalid name : " + reply );
}
this.account.SetName(newName);
}
}
This is my account editor class. At the moment it can only edit the name, but I will add
other edit methods later. The class keeps track of the account it is editing, I pass it a
reference to this account when I construct it. I would use the name editor as follows:
CustomerAccount a = new CustomerAccount("Rob", 50);
AccountEditTextUI edit = new AccountEditTextUI(a);
edit.EditName();
Code Sample 53 Name Editing
This code creates an instance of a customer account. It then creates an editor object and
asks it to edit the name of that account.
Note that the editor class is passed a reference to the IAccount interface, not a
reference to the account class. This means that anything which behaves like an account
can be edited using this class. Note also that the editor remembers the account class
that is being edited so that when I call EditName it can work on that reference.
Threads are also how Windows forms respond to events. You have seen that a “click”
event from a Button component can be made to run an event handler method. The
Windows system actually creates a new thread of execution which runs the event
handler code.
My laptop has four processor cores, which means that it can run four threads at a time.
You can see little graphs under the CPU (Central Processor Unit) Usage History part of
the display showing how busy each processor is. From the look of the above graph, the
leftmost processor and the rightmost processor are quite busy but the middle two
processors are not doing anything. If I stop my program running I get a display like the
one below.
Now all the processors are just ticking over. When we start using more than one thread
we should see more of the graphs climbing up, as my programs run on multiple
processors.
Creating a Thread
Once you have your start point defined you can now create a Thread value:
Thread t1 = new Thread(busyLoopMethod);
The variable t1 now refers to a thread instance. Note that at the moment the thread is
not running, it is waiting to be started. When we start running t1 it will follow the
delegate busyLoopMethod and make a call to the busyloop method.
Starting a Thread
The Thread class provides a number of methods that your program can use to control
what it does. To start the thread running you can use the Start method:
t1.Start();
This is the point at which the thread begins to run.
class ThreadDemo
{
static private void busyLoop()
{
long count;
for (count = 0; count < 1000000000000L; count = count+1)
{
}
}
t1.Start();
busyLoop();
}
}
Code Sample 55 Two Threaded Busy Loop
The above code creates a thread called t1 and starts it running the busyLoop method.
It also calls busyLoop directly from the Main method. This means that there are two
processes active. This changes the Task Manager display:
Now more of the usage graphs are showing activity and the CPU usage is up from 25%
to 50% as our program is now using more processors.
All the processors are now maxed out, and the CPU usage is up to 100%. If you run
this code you might actually find that the machine becomes slightly less responsive,
and that all the cooling fans come on full blast.
overDraftCount variable is declared static so that there is only one copy of this
variable in the program. This single copy can then be updated by calls of
countOverdraftRange that are running on multiple threads.
Our program could now start two threads, each of which will work on different halves
of the account array:
static private void firstHalf()
{
countOverdraftRange(0,5000000);
}
complete without being interrupted. You can do this by using a feature called mutual
exclusion or mutex. We can return to our train analogy here.
Pausing Threads
As you can see above, one way to “pause” a thread is to create a loop with an
enormous limit value. This will certainly pause your program, but at the expense of any
other threads that want to run. If you just want your program to pause, perhaps to allow
the user to read the output or to wait a little while for something to happen you should
use the Sleep method which is provided by the Thread class:
Thread.Sleep(500);
This method is given the number of milliseconds (thousandth’s of a second) that the
execution is to pause. The above call would pause a program for half a second.
Joining Threads
You might want to make one thread wait for another to finish working. A thread
finishes when it exits the method that was called when it started. In our examples
above, each thread will end when the call of busyloop finishes. A thread instance
provides a Join method that can be called to wait for another thread to complete
operation.
t1.Join();
This would cause the executing thread to wait until the thread t1 finishes.
Thread Control
The Thread class provides a set of methods that you can use to control the execution
of a thread. You can abort a thread by calling its Abort method:
t1.Abort();
This asks the operating system to destroy that thread and remove it from memory.
If you don’t want to destroy a thread, but simply make it pause for a while, you can call
the Suspend method on the thread:
t1.Suspend();
The thread is put to sleep until you call the Resume method on that thread.
t1.Resume();
This is especially important when you consider that a given project may have many
people working on it.
To do this we have to solve two problems:
• how we physically spread the code that we write around a number of files
• how we logically identify the items in our program.
The two problems are distinct and separate and C# provides mechanisms for both. In
this section we are going to see how a large program can be broken down into a
number of different chunks.
programs will run and create accounts when they need them. So, the compiler cannot
make an executable file, since it does not know where the program should start.
Note that I have made the Account class public. This is so that classes in other files
can make use of it. You can apply the protection levels to classes in the same way that
you can protect class members. Generally speaking your classes will be public if you
want them to be used in libraries.
Creating a Library
I solve this problem by asking the compiler to produce a library instead. I use the target
option to the compile command. Options are a way of modifying what a command
does. The compiler can tell that it is being given an option because options always start
with a slash character:
csc /target:library AccountManagement.cs
The compiler will not now look for a Main method, because it has been told to produce
a library rather than a program. If I look at what has been created I find that the
compiler has not made me an executable, instead it has made me a library file:
AccountManagement.dll
The language extension dll stands for dynamic link library. This means that the content
of this file will be loaded dynamically as the program runs.
Using a Library
Now I have a library I next have to work out how to use it. Firstly I'm going to create
another source file called AccountTest.cs. This contains a Main method which will
use the Account class:
using System;
class AccountTest
{
public static void Main ()
{
Account test = new Account();
test.PayInFunds (50);
Console.WriteLine ("Balance:" + test.GetBalance());
}
}
This makes a new account, puts 50 pounds in it and then prints out the balance. If I try
to compile it I get a whole bunch of errors:
AccountTest.cs(5,3): error CS0246: The type or namespace name
'Account' could not be found (are you missing a using directive or
an assembly reference?)
AccountTest.cs(6,3): error CS0246: The type or namespace name
'test' could not be found (are you missing a using directive or an
assembly reference?)
AccountTest.cs(7,37): error CS0246: The type or namespace name
'test' could not be found (are you missing a using directive or an
assembly reference?)
The problem is that the compiler does not know to go and look in the file
AccountManagement.cs to find the Account class. This means that it fails to create
test, which causes further errors.
To solve the problem I need to tell the compiler to refer to AccountManagement to
find the Account class:
csc /reference:AccountManagement.dll AccountTest.cs
The reference option is followed by a list of library files which are to be used. In this
case there is just the one file to look at, which is the library that contains the required
class. The compiler now knows where to find all the parts of the application, and so it
can build the executable program.
5.6.2 Namespaces
We can use library files to break up our solution into a number of files. This makes
management of the solution slightly easier. But we also have another problem. We
don't just want to break things into physical chunks. We also want to use logical ones
as well.
If you are not sure what I mean by this, consider the situation in our bank. We have
decided that Account is a sensible name for the class which holds all the details of a
customer account.
But if you consider the whole of the bank operations you find that the word "account"
crops up all over the place. The bank will buy things like paper clips, rubber stamps,
little pens on chains (pre-supplied with no ink in of course) and the like from suppliers.
You could say that the bank has an account with such a supplier. It may well wish to
keep track of these accounts using a computer system. Perhaps the programmers might
decide that a sensible name for such a thing would be Account. Arrgh! We are now
heading for real problems. If the two systems ever meet up we can expect a digital fight
to the death about what "Account" really means. Which would be bad.
We could solve the problem by renaming our account class CustomerBankAccount.
But this would be messy, and mean that at design time we have to make sure that we
name all our classes in a way which will always be unique.
A far better way would be to say that we have a CustomerBanking namespace in
which the word Account has a particular meaning. We can also have an
EquipmentSupplier namespace as well. This prevents the two names from clashing,
in that they are not defined in the same namespace.
A given source file can contain as many namespace definitions and each can contain as
many classes as you like.
Using a namespace
If you are using a lot of things from a particular namespace C# provides a way in
which you can tell the compiler to look in that namespace whenever it has to resolve
the name of a particular item. We do this with the using keyword:
using CustomerBanking ;
When the compiler sees a line like:
Account RobsAccount;
- it automatically looks in the CustomerBanking namespace to see if there is a class
called Account. If there is it uses that. We have already used this technique a lot. The
System namespace is where a lot of the library components are located. We can use
these by means of fully qualified names:
System.Console.WriteLine ( "Hello World" );
However, it is common for most programs to have the line:
using System;
- at the very top. This means that the programmer can just write:
Console.WriteLine ( "Hello World" );
The compiler goes "ah, I'll go and have a look for a thing called Console in all the
namespaces that I've been told to use". If it finds one, and only one, Console then all
is well and it uses that. If it finds two Console items (if I was an idiot I could put a
Console class in my CustomerBanking namespace I suppose) it will complain that
it doesn't know which to use.
Nesting Namespaces
You can put one namespace inside another. This allows you to break things down into
smaller chunks. The System namespace is like this, there is a namespace which is part
of the System namespace which is specifically concerned with Input/Output. You get
to use the items in the System.IO namespace with an appropriate include:
using System.IO ;
In terms of declaring the namespace you do it like this:
namespace CustomerBanking {
namespace Accounts {
// account classes go here
}
namespace Statements {
// statement classes go here
}
namespace RudeLetters {
// rude letter classes go here
}
}
Now I can use the classes as required:
using CustomerBanking.RudeLetters ;
Of course the namespaces that you use should always be carefully designed. But then
again, you'd probably figured that one out already.
We are going to discover that it is hard to talk about XAML without mentioning Visual
Studio, the integrated development environment that lets programmers create
applications which contain a XAML designed user interface connected to C# code
behind.
Visual Studio can synchronise the XAML description of a user interface with the
program code that is connected to it. It also contains graphical editor that can be used
to design the interface itself.
It is perhaps best to regard C#, XAML and Visual Studio as a whole, as they were
designed to work together to make it easy for programmers to create these kinds of
applications.
XML Schema
The XML standard also contains descriptions how to create a schema which describes
a particular document format. For example, in the above the schema for the high score
information would say that a HighScore must contain a PlayerName and a Score
property. It might also say things like the HighScore can contain a Date value (the
date when the high score was achieved) but that this is not required for every
HighScore value.
This system of standard format and schema means that it is very easy for developers to
create data formats for particular purposes. This is helped by the fact that there are a lot
of design tools to help create documents and schemas. The .NET framework even
provides a way by which a program can save an object as a formatted XML document.
In fact the Visual Studio solution file is actually stored as an XML document.
As far as we are concerned, it is worth remembering that XML is useful for this kind of
thing, but at the moment I want to keep the focus on XAML itself.
Unfortunately it turns out that most programmers (including me) are not that good at
designing attractive user interfaces (although I’m sure that you are). In real life a
company will employ graphic designers who will create artistic looking front ends. The
role of the programmer will then be to put the code behind these displays to get the
required job done.
Microsoft designed XAML as a recognition of this issue. It enforces a very strong
separation between the screen display design and the code that is controlled by it. This
makes it easy for a programmer to create an initial user interface which is subsequently
changed by a designer into a much more attractive one. It is also possible for a
programmer to take a complete user interface design and then fit the behaviours behind
each of the display components.
This is a very simple Windows program that I’ve called an “Adding Machine”. You
can use to perform very simple sums. You just enter two numbers into the two text
boxes at the top and then press the equals button. It then rewards you with the sum of
these two numbers. At the moment it is showing us that 0 plus 0 is 0. Each individual
item on the screen is called a UIElement or User Interface element. I’m going to call
these things elements from now on. There are six of them on the screen above:
1. The title “Adding Machine”. This is a block of text with a font size of 18 so
that it stands out.
2. The top textbox, where I can type a number.
3. A text item holding the character +.
4. The bottom textbox, where I can type another number.
5. A button, which we press to perform the sum.
6. A result textbox, which changes to show the result when the button is pressed.
At the moment this is empty, as we haven’t done any sums yet.
Each of these items has a particular position on the screen, particular size of text and
lots of other properties too. We can change the colour of the text in a text box, whether
it is aligned to the left, right or centre of the enclosing box and lots of other things too,
by updating the XAML that describes the page. The actual XAML that describes the
display is as follows:
<StackPanel>
<TextBlock Text="Adding Machine" TextAlignment="Center"
Margin="0,10" FontSize="18"></TextBlock>
<TextBox Name="firstNumberTextBox" Width="100"
Margin="0,10" TextAlignment="Center"></TextBox>
<TextBlock Text="+" TextAlignment="Center" Margin="0,10"></TextBlock>
<TextBox Name="secondNumberTextBox" Width="100"
Margin="0,10" TextAlignment="Center"></TextBox>
<Button Content="Equals" Name="equalsButton" HorizontalAlignment="Center"
Margin="0,10" Click="equalsButton_Click"></Button>
<TextBlock Name="resultTextBlock" Text="" TextAlignment="Center"
Margin="0,10"></TextBlock>
</StackPanel>
If you look carefully you can map each of the elements in the list above into items in
the XAML file. The only thing that is a bit confusing is the StackPanel element. This
is very simple, and terribly useful. Rather than us having to define the position on the
screen of each of the elements, a StackPanel just lets us “pile up” a series of display
elements. The default arrangement is to stack the items down the screen, but you can
also stack items across the screen. You can, and this is really useful, put a
StackPanel inside a StackPanel, so you can make up a stack of rows. This nesting
of elements is a recurring theme inside XAML files.
FrameworkElement
TextBlock Control
TextBox ContentControl
ButtonBase
Button
Above you can see part of the hierarchy that the XAML designers built. The top class
is called FrameworkElement. It contains all the information that is common to all
controls on the screen. Each of the other classes is a child of this class. Children pick
up all the behaviours and properties of their parent class and then add some of their
own. Actually the design is a bit more complex than shown above, the
FrameworkElement class is a child of a class called UIElement, but it shows the
principles behind the controls.
Creating a class hierarchy like this has a lot of advantages. If we want a custom kind of
textbox we can extend the TextBox class and add the properties and behaviours that
we need. As far as the software implementing the XAML system is concerned it can
treat all the controls the same and then ask each control to draw itself in a manner
appropriate to that component.
Our program will manipulate the elements as if they were C# objects, although they
were actually defined in a XAML source file. This works because when the program is
built the XAML system will create objects that match elements described in the XAML
source file.
Properties in Elements
Once we have given our TextBox variable a proper name we can move on to give it all
the properties that are required for this application. We can also change lots of
properties for the textbox including the width of the textbox, the margin (which sets the
position) and so on.
When we talk about the “properties” of Silverlight elements on the page (for example
the text displayed in a TextBox) we are actually talking about property values in the
class that implements the TextBox. In other words, when a program contains a
statement such as:
resultTextBlock.Text = "0";
- This will cause a Set method to run inside the resultTextBlock object which sets
the text on the TextBlock to the appropriate value.
You may be asking the question “Why do we use properties in XAML elements?” It
makes sense to use them in a bank account where I want to be able to protect the data
inside my objects but in a XAML page, where I can put any text I like inside a
TextBlock, there seems to be no point in having validation of the incoming value. In
fact running this code will slow down the setting process. So, by making the Text
value a public string we could make the program smaller and faster, which has to be a
good thing. Right?
Well, sort of. Except that when we change the text on a TextBlock we would like the
text on the XAML page in front of the user to change as well. This is how our adding
machine will display the result. If a program just changed the value of a data member
there would be no way the XAML system could know that the message on the screen
needs to be updated.
However, if the Text member is a property when a program updates it the set
behaviour in the TextBlock will get to run. The code in the set behaviour can update
the stored value of the text field and it can also trigger an update of the display to make
the new value visible. Properties provide a means by which an object can get control
when a value inside the object is being changed, and this is extremely important. The
simple statement:
resultTextBlock.Text = "0";
- may cause many hundreds of C# statements to run as the new value is stored in the
TextBlock and an update of the display is triggered to make the screen change.
Whenever Visual Studio makes a XAML file that describes a page on the display it
also makes a C# program file to go with it. This is where we can put code that will
make our application work. If you actually take a look in the file MainPage.xaml.cs
above you will find that it doesn’t actually contain much code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace sample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Most of the file is using statements which allow our program to make direct use of
classes without having to give the fully formed name of each of them. For example,
rather than saying System.Windows.Controls.Button we can say Button,
because the file contains the line using System.Windows.Controls.
The only methods in the program are the constructor of the MainWindow class. As we
know, the constructor of a class is called when an instance of the class is created. All
the constructor does is call the method InitializeComponent. If you go take a look
inside this method you will find the code that actually creates the instances of the
display elements. This code is automatically created for you by Visual Studio, based on
the XAML that describes your page. It is important that you leave this call as it is and
don’t change the content of the method itself as this will most likely break your
program.
Note that at this point we are deep in the “engine room” of XAML. I’m only really
telling you about this so that you can understand that actually there is no magic here. If
the only C# programs you have seen so far start with a call of the Main method then it
is important that you understand that there is nothing particularly special about a
XAML one. There is a Main method at the base of a XAML application; it starts the
process of building the components and putting them on the screen for the user to
interact with.
The nice thing as far as we are concerned is that we don’t need to worry about how
these objects are created and displayed, we can just use the high level tools or the easy
to understand XAML to design and build our display.
the equals button if we like. We seem to have got a lot of behaviour for very little
effort, which is nice. However, we need to add some business logic of our own now to
get the program to work out the answer and display it.
resultTextBlock.Text = result.ToString();
}
The TextBox objects expose a property called Text. This can be read from or written
to. Setting a value into the Text property will change the text in the textbox. Reading
the Text property allows our program to read what has been typed into the textbox.
The text is given as a string, which must be converted into a numeric value if our
program is to do any sums. You have seen the Parse method before. This takes a
string and returns the number that the string describes. Each of the numeric types
(int, float, double etc.) has a Parse behaviour which will take a string and return
the numeric value that it describes. The adding machine that we are creating can work
with floating point numbers, so the method parses the text in each of the input
textboxes and then calculates a result by adding them together.
Finally the method takes the number that was calculated, converts it into a string and
then sets the text of the resultTextBlock to this string. ToString is the reverse of
Parse, the “anti-parse” if you like. It provides the text that describes the contents of an
object. In the case of the float type, this is the text that describes that value.
Now we have our code that works out the answer, we just have to find a way of getting
it to run when the user presses the equals button.
instances of that delegate which refer to a method in an object. Delegates are very
powerful, but can be a bit tricky to get your head around. Fortunately we don’t have to
worry about how delegates work just at the moment; because we can get Silverlight
and Visual Studio to do all the hard work for us.
Events in XAML
In C# an event is delivered to an object by means of a call to a method in that object. In
this respect you can regard an event and a message as the same thing. From the point of
view of our adding machine we would like to have a particular method called when the
"equals" button is pressed by the user. This is the only event that we are interested in.
When the event fires we want it to call the calculateResult method above. If we
take a look back at the XAML for the button we can see how this is achieved.
<Button Content="Equals" HorizontalAlignment="Center" Margin="0,10"
Name="equalsButton" Click="equalsButton_Click"></Button>
The button element has a name, equalsButton, and a property called Click. This is
set to the value equalsButton_Click. This is the link between the XAML (which is
the declarative language that describes the page on the screen) and C# (which is the
programming language that will actually do something for us).
For this to work the page which contains the equalsButton display element must
contain a method called equalsButton_Click. Otherwise the program will not build
correctly. This is the method that provides the behaviour for the equals button:
private void equalsButton_Click(object sender, RoutedEventArgs e)
{
calculateResult();
}
The event handler must have the correct signature so that it can be given parameters
that describe the event.
If you are wondering how all this works, it actually uses delegates to manage the
events that are passed from the Windows display manager into the program running on
it. As you saw earlier, a delegate is an object that represents a method in an instance of
a class. If you think about it; that is exactly what we need here. We need a way of
telling the window management system in Windows that when the equals button is
clicked we would like this method to be called. A delegate object is perfect for this
task. The Button display element contains a property called Click. A program can
add delegate objects to this property so that when the window manager detects that the
button has been pressed it can call that method. In other words, somewhere in the code
generated for the XAML above is the statement:
equalsButton.Click +=new RoutedEventHandler(equalsButton_Click);
The += operator is a bit confusing here, but what it really means is “add a delegate
object to the list of those that will be called when the button is clicked by the user”.
The delegate is of type RoutedEventHandler and when an instance of the delegate
is constructed it is given the identifier of the method it is going to refer to. If a program
ever needs to disconnect a handler from an event it can use the -= operator to do this.
For example, the user might type in numbers as above. We already know that this will
cause problems with the Parse method, which will promptly throw an exception and
stop the program. We also know that we can catch exceptions and deal with them. In
the case of the program above the best way to deal with these kinds of errors is to
display a message box:
private void calculateResult()
{
try
{
float v1 = float.Parse(firstNumberTextBox.Text);
float v2 = float.Parse(secondNumberTextBox.Text);
}
Code Sample 57 WPF Adding Machine
This version of calculateResult catches the exception that would be thrown by
Parse and then uses the MessageBox class to display an error message.
The MessageBox class is a static class that is part of the XAML library. There are
several versions of the Show method so that you can display different versions of the
message box. The one I used just accepts two strings. One is the title of the box. The
other is the message to be displayed. The user can cancel the message by pressing the
OK button.
Note that this method is not a very good one, in that it doesn’t say which of the two
numbers was in error.
5.8 Debugging
Some people are born to debug. Not everyone is good at debugging, some will always
be better than others. Having said that there are techniques which you can use to ease
the process, and we are going to explore some of these here. The good news is that if
you use a test driven approach to your development the number of faults that are found
by the users should be as small as possible, but there will still be some things that need
to be fixed.
Incidentally, the reason why problems with programs are called bugs is that the
original one was caused by an actual insect which got stuck in some contacts in the
computer, causing it to fail. This is not however how most bugs are caused. It is very
rarely that you will see your program fail because the hardware is faulty, I've been
programming for many years and only seen this in a handful of occasions. The sad
thing is that most of the bugs in programs have been put there by programmers. In
other words, debugging is working very hard to find out how stupid you were in the
first place.
Faults which sometimes happen are a pain. What this means is that you do not have a
definite sequence of events which causes the system to fail. This does not mean that
there is no sequence (unless you are suffering from a hardware induced transient of
some kind – which is rather rare) but that you have not found the sequence yet.
An example would be a print function which sometimes crashes and works at other
times. You might track this down to the number of pages printed, or the amount of text
on the page, or the size of the document which is being edited when the print is
requested.
The manifestation of a fault may be after the error itself has actually occurred, for
example a program may fail when an item is removed from a database, but the error
may be in the routine which stored the item, or in code which overwrote the memory
where the database lives.
A fault may change or disappear when the program itself is changed; errors which
overwrite memory will corrupt different parts of the program if the layout of the code
changes. This can lead to the most annoying kind of fault, where you put in extra print
statements to find out more about the problem, and the problem promptly disappears!
If you suspect such an error, your first test is to change the code and data layout in
some way and then re-run the program. If the fault changes in nature this indicates
problems with program or data being corrupted.
5.8.2 Bugswatting
You can split faults into other categories, where the program crashes (i.e. stops
completely) or when it does the wrong thing. Surprisingly, crashes are often easier to
fix. They usually point to:
• a state which is not catered for (make sure that all selection statements
have a default handler which does something sensible and that you use
defensive programming techniques when values are passed between
modules)
• programs that get stuck into loops, do – while constructions which
never fail, for loops which contain code which changes the control
variable, methods that call themselves by mistake and recurse their
way into stack overflow
• an exception that is not caught properly
If your program does the wrong thing, this can be harder to find. Look for:
• use of un-initialised members of classes
• typographical errors (look for incorrectly spelt variable names,
incorrect comparison operators, improperly terminated comments)
• logical errors (look for faults in the sequence of instructions, invalid
loop termination's, wrongly constructed logical conditions)
As I said above, some folks are just plain good at finding bugs. Here are some tips:
Don't make any assumptions. If you assume that "the only way it could get here is
through this sequence" or "there is no way that this piece of code could be obeyed" you
will often be wrong. Rather than make assumptions, add extra code to prove that what
you think is happening is really happening.
do a payroll run at that time and fills up all the scratch space, or the loading department
turn on the big hoist and inject loads of noise into the mains.
Leave the problem alone for a while. Go off and do something different and you may
find that the answer will just appear. Alternatively you may find the answer as soon as
you come back to the problem.
Remember that although the bug is of course impossible, it is happening. This means
that either the impossible is happening, or one of your assumptions that it is impossible
is wrong!
Can you get back to a state where the bug was not present, and then look at the changes
made since? If the system is failing as a result of a change or, heaven forbid, a bug fix,
try to move back to a point where the bug is not there, and then introduce the changes
until the bug appears. Alternatively, look carefully at how the introduction of the
feature affects other modules in the system. A good Source Code Control System is
very valuable here, in that it can tell you exactly what changes have been made from
one version to the next.
One thing that I should make clear at this point is that the process of debugging is that
of fixing faults in a solution which should work. In other words you must know how
the program is supposed to work before you try and fix problems with what it actually
does. I have been nearly moved to tears by the sight of people putting in another loop
or changing the way their conditions operate to "see if this will make the program
work". Such efforts are always doomed, just like throwing a bunch of electrical
components at the wall and expecting a DVD player to land on the floor is also not
going to work.
This means that you need to evaluate the impact of the faults that get reported to you,
prioritise them and manage how they are dealt with. You also need to be aware of the
context of the development. For example, a fault in a video game is much less of a
problem than one in an air traffic control system.
The key to making software that is as perfect as possible is to make sure that you have
a good understanding of the problem that you are solving, that you know how to solve
it before you start writing code and that you manage your code production process
carefully. Read some of the recommended texts at the end of this document for more
on this aspect of programming.
How to be a programmer
This web site is also worth a read, as it covers the behaviours of a programmer very
well indeed:
http://samizdat.mines.edu/howto/HowToBeAProgrammer.html
6 Glossary of Terms
Abstract
Something which is abstract does not have a "proper" existence as such. When writing
programs we use the word to mean "an idealised description of something". In the case
of component design an abstract class contains descriptions of things which need to be
present, but it does not say how they are to be realised. In C# terms a class is abstract if
it is marked as such, or if it contains one or more method which is marked as abstract.
You can't make an instance of an abstract class, but you can use it as the basis of, or
template for, a concrete one. For example, we may decide that we need many different
kinds of receipt in our transaction processing system: cash receipt, cheque receipt,
wholesaler receipt etc. We don't know how each particular receipt will work inside, but
we do know those behaviours which it must have to make it into a receipt.
We can therefore create an abstract Receipt class which serves as the basis of all the
concrete ones. Each "real" receipt class is created by extending the parent, abstract one.
This means that it is a member of the receipt family (i.e. it can be treated as a Receipt)
but it works in its own way.
Accessor
An accessor is a method which provides access to the value managed within a class.
Effectively the access is read only, in that the data is held securely in the class but code
in other classes may need to have access to the value itself. An accessor is implemented
as a public method which will return a value to the caller. Note that if the thing being
given access to is managed by reference the programmer must make sure that it is OK
for a reference to the object is passed out. If the object is not to be changed it may be
necessary to make a copy of the object to return to the caller.
Base
base is a C# keyword which has different meanings depending on the context in which
it is given. It is used in a constructor of a child class to call the constructor in the
parent. It is also used in overriding methods to call the method which they have
overridden.
Call
When you want to use a method, you call it. When a method is called the sequence of
execution switches to that method, starting at the first statement in its body. When the
end of the method, or the return statement, is reached the sequence of execution returns
to the statement immediately following the method call.
Class
A class is a collection of behaviours (methods) and data (properties). It can be used to
represent a real world item in your program (for example bank account). Whenever you
need to collect a number of things into a single unit you should think in terms of
creating a class.
Code Reuse
A developer should take steps to make sure that a given piece of program is only
written once. This is usually achieved by putting code into methods and then calling
them, rather than repeating the same statements at different parts of a program. The use
of class hierarchies is also a way of reusing code. You only need to override the
methods that you want to update.
Cohesion
A class has high cohesion if it is not dependent on/coupled to other classes.
Collection
The C# library has the idea of a collection as being a bunch of things that you want to
store together, for example all the players in a football team or all the customers in a
bank. One form of a collection is an array. Another is the hashtable, which allows you
to easily find a particular item based on a key value in that item. A collection class will
support enumeration which means that it can be asked to provide successive values to
the C# foreach construction.
Whenever you want to store a number of things together you should consider using a
collection class to do this for you. The collection classes can be found in the
System.Collections namespace.
Compiler
A compiler takes a source file and makes sense of it. The compiler will produce an
executable file which is run. Writing compilers is a specialised business, they used to
be written in assembly language but are now constructed in high level languages (like
C#!). A compiler is a large program which is specially written for a particular computer
and programming language. Most compilers work in several phases. The first phase,
the pre-processor, takes the source which the user has written and then finds all the
individual keywords, identifiers and symbols producing a stream of program source
which is fed to the "parser" which ensures that the source adheres to the grammar of
the programming language in use. The final phase is the code generator, which
produces the executable file which is later run by the host.
Component
A component is a class which exposes its behaviour in the form of an interface. This
means that rather than being thought of in terms of what it is (for example a
BabyCustomerAccount) it is thought of in terms of what it can do (implement the
IAccount interface to pay in and withdraw money). When creating a system you
should focus on the components and how they interact. Their interactions are expressed
in the interfaces between them.
Constructor
A constructor is a method in a class which is called as a new instance of that class is
created. Programmers use constructors to get control when an instance is created and
set up the values inside the class. If a class is a member of a hierarchy, and the parent
class has a constructor, it is important when making the child that you ensure the parent
constructor is called correctly. Otherwise the compiler will refuse to compile your
program.
Coupling
If a class is dependent on another the two classes are said to be coupled. Generally
speaking a programmer should strive to have as little coupling in their designs as
possible, since it makes it harder to update the system.
Coupling is often discussed alongside cohesion, in that you should aim for high
cohesion and low coupling.
Creative Laziness
It seems to me that some aspects of laziness work well when applied to programming.
Code reuse, where you try and pick up existing code, is a good example of this.
Making sure the spec. is right before you do anything is another way of saving on
work. However, structuring the design so that you can get someone else to do a lot of
the work is probably the best example of creative laziness in action.
Declarative language
A declarative language tells a computer system about stuff. It doesn’t give instructions
that explain how to perform an action; it just makes the system aware of the fact that
something exists and has a particular set of properties.
C# contains declarations; this is how a program can create variables.
int i;
This declaration creates an integer variable which is identified by the name i.
However, a C# program also contains statements which tell the computer how to
perform an action.
i = i + 1;
This statement changes the value in i, making it larger by 1. The ability to do this
means that C# is not a declarative language. The markup language XAML however, is
declarative. XAML was designed to express the design of a page. All a XAML source
file contains is descriptions of items.
<TextBox Name="firstNumberTextBox" Text="0"
VerticalAlignment="Top" Width="460"
TextAlignment="Center">
</TextBox>
This chunk of XAML describes a TextBox display element. It gives the width, the
initial text, the alignment and the name of the element. However, it does not, and can
never, tell the system what to do with the element, or any behaviour that it has. This is
because XAML does not provide a way of expressing behaviour; it is simply there to
tell the display system about stuff.
Delegate
A delegate is a type safe reference to a method. A delegate is created for a particular
method signature (for example this method accepts two integers and returns a float). It
can then be directed at a method in a class which matches that signature. Note that the
delegate instance holds two items, a reference to the instance/class which contains the
method and a reference to the method itself. The fact that a delegate is an object means
that it can be passed around like any other.
Delegates are used to inform event generators (things like buttons, timers and the like)
of the method which is to be called when the event they generate takes place.
Dependency
In general, too much dependency in your designs is a bad thing. A dependency
relationship exists between two classes when a change in code in one class means that
you might have to change the other as well. It usually means that you have not properly
allocated responsibility between the objects in your system and that two objects are
looking after the same data. As an example see the discussion of the CustomerAccount
and ChildAccount Load method on page 157.
Dependency is often directional. For example a user interface class may be dependent
on a business object class (if you add new properties to the business object you will
need to update the user interface). However, it is unlikely that changes to the way that
the user interface works will mean that the business object needs to be altered.
Event
An event is some external occurrence which your program may need to respond to.
Events include things like mouse movement, keys being hit, windows being resized,
buttons being pressed, timers going tick etc. Many modern programs work on the basis
of events which are connected to methods. When the event occurs the method is called
to deliver notification. Windows components make use of delegates (a delegate is a
type safe reference to a method) to allow event generators to be informed of the
method to be called when the event takes place.
Exception
An exception is an object that describes something bad that has just happened.
Exceptions are part of the way that a C# program can deal with errors. When a running
program gets to a position where it just can’t continue (perhaps a file cannot be opened
or an input value makes no sense) it can give up and “throw” an exception:
throw new Exception("Oh Dear");
The Exception object contains a Message property that is a string which can be used
to describe what has gone wrong. In the above example the message would be set to
“Oh Dear”.
If the exception is not “caught” the program will end at that point. You can make a
program respond to exceptions by enclosing code that might throw an exception in a
try – catch construction. When the exception is thrown the program transfers execution
to the code in the catch clause:
try
{
// code that might throw an exception
}
catch (Exception e)
{
// code that is obeyed if an exception is thrown
// e is a reference to the exception that was thrown
}
finally
{
// code in here is always obeyed, whether the exception
// was thrown or not
}
A try – catch construction can also contain a finally clause, which contains code that is
executed whether or not the exception is thrown.
Hierarchy
A hierarchy is created when a parent class is extended by a child to produce a new
class with all the abilities of the parent plus new and modified behaviours specific to
the requirements of the child. Extending the child produces a further level of hierarchy.
The classes at the top of the hierarchy should be more general and possibly abstract
(for example BankAccount) and the classes at the lower levels will be more specific
(for example ChildBankAccount).
Immutable
An immutable object cannot be changed. If an attempt is made to change the content of
an immutable object a new object is created with the changed content and the "old" one
remains in memory. The string class is immutable. This gives strings a behaviour
similar to value types, which makes them easier to use in programs.
Inheritance
Inheritance is the way in which a class extends a parent to allow it to make use of all
the behaviours and properties the parent but add/customise these for a slightly different
requirement. For more detail see the description of hierarchy.
Interface
An interface defines a set of actions. The actions are defined in terms of a number of
method definitions. A class which implements an interface must contain code for each
of the methods. A class which implements an interface can be referenced purely in
terms of that interface. Interfaces make it possible to create components. We don't care
precisely what the component is, as long as it implements the interface it can be
thought of purely in terms of that ability.
Library
A library is a set of classes which are used by other programs. The difference between
a library and a program is that the library file will have the extension .dll (dynamic link
library) and will not contain a main method.
Machine code
Machine Code is the language which the processor of the computer actually
understands. It contains a number of very simple operations, for example move an item
from the processor into memory, or add one to an item in the processor. Each particular
range of computer processors has its own specific machine code, which means that
machine code written for one kind of machine cannot be easily used on another.
Member
A member of a class is declared within that class. It can either do something (a method)
or hold some data (variable). Methods are sometimes called behaviours. Data members
are sometimes called properties.
Metadata
Metadata is data about data. It operates at all kinds of levels. The fact that the age value
is held as an integer is metadata. The fact that it cannot be negative is more metadata.
Metadata must be gathered by the programmer in consultation with the customer when
creating a system.
Method
A method is a block of code preceded by a method signature. The method has a
particular name and may return a value. It may also accept a parameter to work on.
Methods are used to break a large program up into a number of smaller units, each of
which performs one part of the task. They are also used to allow the same piece of
program to be used in lots of places in a large development. If a method is public it can
be called by code other classes. A public method is how an object exposes its
behaviours. A message is delivered to an object by means of a call of a method inside
that object.
Mutator
A mutator is a method which is called to change the value of a member inside an
object. The change will hopefully be managed, in that invalid values will be rejected in
some way. This is implemented in the form of a public method which is supplied with
a new value and may return an error code.
Namespace
A namespace is an area within which a particular name has a particular meaning.
Namespaces let you reuse names. A programmer creating a namespace can use any
name in that namespace. A fully qualified name of a resource is prefixed by the
namespace in which the name exists. A namespace can contain another namespace,
allowing hierarchies to be set up. Note that a namespace is purely logical in that it does
not reflect where in the system the items are physically located, it just gives the names
by which they are known. C# provides the using keyword to allow namespaces to be
"imported" into a program.
Overload
A method is overloaded when one with the same name but a different set of parameters
is declared in the same class. Methods are overloaded when there is more than one way
of providing information for a particular action, for example a date can be set by
providing day, month, year information or by a text string or by a single integer which
is the number of days since 1st Jan. Three different, overloaded, methods could be
provided to set the date, each with the same name. In that case the SetDate method
could be said to have been overloaded.
Override
Sometimes you may want to make a more specialized version of an existing class. This
may entail providing updated versions of methods in the class. You do this by creating
a child class which extends the parent and then overriding the methods which need to
be changed. When the method is called on instances of the child class, the new method
is called, not the overridden one in the parent. You can use the base keyword to get
access to the overridden method if you need to.
Portable
When applied to computer software, the more portable something is the easier it is to
move it onto a different type of computer. Computers contain different kinds of
processors and operating systems which can only run programs specifically written for
them. A portable application is one which can be transferred to a new processor or
operating system with relative ease. High Level languages tend to be portable, machine
code is much harder to transfer.
Private
A private member of a class is only visible to code in methods inside that class. It is
conventional to make data members of a class private so that they cannot be changed
by code outside the class. The programmer can then provide methods or C#
properties to manage the values which may be assigned to the private members.
The only reason for not making a data member private is to remove the performance
hit of using a method to access the data.
Property
A property is an item of data which is held in an object. An example of a property of a
BankAccount class would be the balance of the account. Another would be the name of
the account holder. The C# language has a special construction to make the
management of properties easy for programmers.
Protected
A protected member of a class is visible to methods in the class and to methods in
classes which extend this class. It is kind of a half way house between private (no
access to methods outside this class) and public (everyone has access). It lets you
designate members in parent classes as being visible in the child classes.
Public
A public member of a class is visible to methods outside the class. It is conventional to
make the method members of a class public so that they can be used by code in other
class. A public method is how a class provides services to other classes.
Reference
A reference is a bit like a tag which can be attached to an instance of a class. The
reference has a particular name. C# uses a reference to find its way to the instance of
the class and use its methods and data. One reference can be assigned to another. If you
do this the result is that there are now two tags which refer to a single object in
memory.
Signature
A given C# method has a particular signature which allows it to be uniquely identified
in a program. The signature is the name of the method and the type and order of the
parameters to that method:
void Silly(int a, int b) – has the signature of the name Silly and two int
parameters.
void Silly(float a, int b) – has the signature of the name Silly and an float
parameter followed by an integer parameter. This means that the code:
Silly(1, 2) ;
- would call the first method, whereas:
Silly(1.0f, 2) ;
- would call the second.
Note that the type of the method has no effect on the signature.
Source file
You prepare a source file with a text editor of some kind. It is text which you want to
pass through a compiler to produce a program file for execution.
Static
In the context of C# the keyword static makes a member of a class part of a class
rather than part of an instance of the class. This means that you don’t need to create an
instance of a class to make use of a static member. It also means that static members
are accessed by means of the name of their class rather than a reference to an instance.
Static members are useful for creating class members which are to be shared with all
the instances, for example interest rates for all the accounts in your bank.
Stream
A stream is an object which represents a connection to something which is going to
move data for us. The movement might be to a disk file, to a network port or even to
the system console. Streams remove the need to modify a program depending on where
the output is to be sent or input received from.
Structure
A structure is a collection of data items. It is not managed by reference, and structures
are copied on assignment. Structures are also passed by value into methods. Structures
are useful for holding chunks of related data in single units. They are not as flexible as
objects managed by reference, but they are more efficient to use in that accessing
structure items does not require a reference to be followed in the same way as for an
object.
Subscript
This is a value which is used to identify the element in an array. It must be an integer
value. Subscripts in C# always start at 0 (this locates, confusingly, the first element of
the array) and extend up to the size of the array minus 1. This means that if you create a
four element array you get hold of elements in the array by subscript values of 0,1,2 or
3. The best way to regard a subscript is the distance down the array you are going to
move to get the element that you want. This means that the first element in the array
must have a subscript value of 0.
Syntax Highlighting
Some program editors (for example Visual Studio) display different program elements
in different colours, to make it easier for the programmer to understand the code.
Keywords are displayed in blue, strings in red and comments in green. Note that the
colours are added by the editor, and there is nothing in the actual C# source file that
determines the colour of the text.
Test harness
The test harness will contain simulations of those portions of the input and output
which the system being tested will use. You put your program into a test harness and
then the program thinks it is in the completed system. A test harness is very useful
when debugging as it removes the need for the complete system (for example a
trawler!) when testing.
This
this is a C# keyword which has different meanings depending on the context in which
it is given. It is used in a constructor of a class to call another constructor. It is also
used as a reference to the current instance, for use in non-static methods running inside
that instance.
Typesafe
We have seen that C# is quite fussy about combining things that should not be
combined. Try to put a float value into an int variable and the compiler will get cross at
this point. The reason for this is that the designers of the language have noticed a few
common programming mistakes and have designed it so that these mistakes are
detected before the program runs, not afterwards when it has crashed. One of these
mistakes is the use of values or items in contexts where it is either not meaningful to do
this (put a string into a bool) or could result in loss of data or accuracy (put a double
into a byte). This kind of fussiness is called type safety and C# is very big on it. Some
other languages are much more relaxed when it comes to combining things, and work
on the basis that the programmer knows best. They assume that just because code has
been written to do something, that thing must be the right thing.
C# is very keen on this (as am I). I think it is important that developers get all the help
they can to stop them doing stupid things, and a language that stops you from
combining things in a way that might not be sensible is a good thing in my book.
Of course, if you really want to impose your will on the compiler and force it to
compile your code in spite of any type safety issues you can do this by using casting.
Unit test
A unit test is a small test which exercises a component and ensures that it performs a
particular function correctly. Unit tests should be written alongside the development
process so that they can be applied to code just after (or in test drive development just
before) the code is written.
Value type
A value type holds a simple value. Value types are passed as values into method calls
and their values are copied upon assignment; i.e. x = y causes the value in y to be
copied into x. Changes to the value in x will not affect the value of y. Note that this is
in contrast to reference types where the result of the assignment would make x and y
refer to the same instance. Virtual Method
A method is a member of a class. I can call the method to do a job. Sometimes I may
want to extend a class to produce a child class which is a more specialized version of
that class. In that case I may want to replace (override) the method in the parent with a
new one in the child class. For this to take place the method in the parent class must
have been marked as virtual. Only virtual methods can be overridden. Making a
method virtual slightly slows down access to it, in that the program must look for any
overrides of the method before calling it. This is why not all methods are made virtual
initially.
Index
tests 133
class 15
class members 94
( Close 75
() 16, 18 code reuse 116
column printing 47
comments 34
/ compiler 11
/* 34 components 109
computer 2
data processing 3
; embedded system 4
; 17 hardware & software 2
program 3
programming 4
{ condition 35
{ 16 Console 17
constants 37
constructor 102
+ chaining 122
+ 19 custom 103
default 103
failure 107
A management 105
abstract overloading 105
classes and interfaces 123 parameters 103
methods 123 context 20
references to abstract classes 125 continue 43
accessor 97, 134 CPU 168
argument 50 custom constructors 103
ArrayList 144
access element 145 D
find size 145
remove element 145 data 3, 22
search 146 data protection 118
arrays 62 default 72
elements 63 default constructor 103
subscripts 62 delegate 192
two dimensional 64 delegates 136
assignment 17 pointers 137
assignments 45 Dictionary 147
double 16
B
E
base method 119, 127
block 37 elements 63
boolean 27 enumerated types 79
brace 16 Equals method 128
break 42 escape sequence 25
Button 188 events 136
exception 176
class 176
C multiple catches 177
C 10 throwing 177
camel case 28 type 176
case 72 expressions 28
casting 30 data types 31
chain saw 10 operands 29
char 25, 131 operators 29
case 132
F replace 120
sealed 121
files stopping overriding 121
streams 153 virtual 118
foreach 154 mutator 95, 134
fridge 2
fully qualified name 75
N
G namespace 15, 181
global 182
Generics 144, 146 nesting 183
global namespace 182 separate files 184
gozzinta 17 using 183
GUID 116 namespaces 75
narrowing 30
H nested blocks 59
nesting namespaces 183
hash table 142 new 89, 102
Hashtable 143
HTML 185
O
I object class 126
object oriented 11
identifier 13, 27 objects 86, 93, 122
if 35 container 140
immutable 131 equals 128
information 3 factory method 152
inheritance 116 key 143
integers 23 properties 134
interface this 130
abstraction 109 operands 29
design 115 operating system 3
implementing 111 operators 29
implementing multiple 114 combining logical 36
reference 112 priority 29
relational 35
K unary 44
out parameters 56
keyword 13
overflow 23
overloading
L constructors 105
overriding 117
Length 132
library 180
List class 146 P
literal values 22, 31
parameters 18, 49
loops 39
parenthesis 19
break 42
Parse 18
continue 43
pause 173
do - while 40
plumber 5
for 41
pointers 137
while 40
print formatting 46
print placeholders 46
M priority 29
private 95, 96
member protection 95
program
metadata 7
Main 15
methods 13, 48
program flow 34
base method 119
programmer 2
Main 13
Programmers Point
overriding 117
Always provide an equals behaviour 129 Users have strong opinions about the user interface
Avoid Many Dimensions 66, 69, 70 195
Block Copy is Evil 117 Version Control and Change Management 181,
Break Down Your Conditions 37 195, 197
Bug fixes cause bugs 197 programming languages 9
Casts Add Clarity 32 properties 94, 133
Check your maths 23 in interfaces 135
Choose Variable Types Carefully 27 public 96
Clever is not always Clever 42 punctuation 21
Construction Should Be Planned 107, 108
Data Structures are Important 93 R
Delegates are strong magic 168, 169
Design wth Methods 52 ReadLine 17
Design Your Class Construction Process 122 recipie 12
Design your error exceptions yourself 177 reference 88, 89, 91
Design your fault reporting 195 parameters 55
Document your Side Effects 56 to abstract class 125
Don’t use new fangled stuff just because it is there replacing methods 120
148 return 50
Don't Replace Methods 121
Enums are Good 79, 81 S
Every Message Counts 166
Flipping Conditions 43 schema 186
Fully Qualified Names are Good 184 scope 79, 91
Give Your Variables Sensible Names 28 sealed 121
Good Communicators 9 searching 142
Great Programmers 12 semicolon 17
Importance of Hardware 4 source files 178
Importance of Specification 6 StackPanel 188
Interfaces are just promises 115 Star Trek 3
Internationalise your code 109, 111 statement 13
Know Your Data Source 16 returning values 45
Langauges do Help 56 static 15, 99
Learn to use Visual Studio 185 data 99
Make sure you use the right equals 128 methods 100
Metadata 7 story telling 33
Metadata members Members and Methods 96 stream 73
Not everything should be possible 94 streams 153
Pace Your Comments 34 StreamWriter 74
Plan for Failure 58 string 25, 131
Plan Your Variables 61, 65 comparison 132
private data and public methods 96, 98 editing 132
Production Code 161 immutable 131
Program Layout 21 Length 132
Programming Languages 10 literal 19
Programs often fail in the error handlers 178 StringBuilder 133
Static Data Members are Useful and Dangerous 100 structures 82
Static Method Members can be used to make accessing 83
libraries 102 defining 82
Streams are wonderful 154 subscripts 62
Strive for Simplicity 45 switch 70, 71
Structures are Crucial 85, 86 case 72
Stupid Computers 10 System namespace 15
Switches are Good 73
There is only so much you can do 152 T
Try to avoid the garbage man 91
Use break With Care 43 text based editing 165
Use Numbers Not Messages 163 TextBox 188
Use Simple Variable Types 25 this 130
Thread 169
Monitor 173
mutex 173
Sleep 173
Start 170
threads 167
ThreadStart 169
ToString 126
ToUpper 132
Trim 133
U
unicode 26
user 2
using 15
V
value parameters 54
variable scope 58
variables 12, 22
arrays 62
assignment 28
bool 27
char 25
declaring 22
double 16
float 24
list 16
string 26
structures 82
text 25
types 22
verbatim 26
virtual methods 118
Visual Studio 185
void 15
W
widening 30
Wizard of Oz 184
WriteLine 19
X
XAML 185
XML 185