C Programming Yellow Book Rob Miles pdf download
C Programming Yellow Book Rob Miles pdf download
https://ebookmeta.com/product/c-programming-yellow-book-rob-
miles/
https://ebookmeta.com/product/begin-to-code-with-c-1st-edition-
rob-miles/
https://ebookmeta.com/product/book-1st-edition-david-miles-
natalie-hoopes-illustrator/
https://ebookmeta.com/product/the-python-book-1st-edition-rob-
mastrodomenico/
https://ebookmeta.com/product/the-reemergence-of-civil-society-
in-eastern-europe-and-the-soviet-union-zbigniew-rau/
My Dark Psycho 1st Edition Lovebite Shorts
https://ebookmeta.com/product/my-dark-psycho-1st-edition-
lovebite-shorts/
https://ebookmeta.com/product/the-struggle-for-development-and-
democracy-volume-1-new-approaches-1st-edition-alessandro-
olsaretti/
https://ebookmeta.com/product/cat-the-guardians-trust-5-1st-
edition-beth-linton/
https://ebookmeta.com/product/the-last-judgement-1st-edition-r-d-
shah/
https://ebookmeta.com/product/global-warming-and-the-climate-
crisis-science-spirit-and-solutions-1st-edition-bruce-e-
johansen-2/
The Universal Declaration of Human Rights and the
Holocaust An Endangered Connection Johannes Morsink
https://ebookmeta.com/product/the-universal-declaration-of-human-
rights-and-the-holocaust-an-endangered-connection-johannes-
morsink/
C# Programming
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
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.