You are on page 1of 59

ICTPRG406

Apply introductory object-oriented skills

Learner Guide
© Copyright, 2016 by North Coast TAFEnow

Date last saved: 21 January 2016 by Amanda Walker Version: 1.0 # of Pages = 57

John Chapman – Content writer and course adviser

TAFEnow Resource Development Team – Instructional and


graphic design

Copyright of this material is reserved to the Crown in the right of the State of New South Wales.

Reproduction or transmittal in whole, or in part, other than in accordance with the provisions of the Copyright Act, is
prohibited without written authority of North Coast TAFEnow.

Disclaimer: In compiling the information contained within, and accessed through, this document ("Information")
DET has used its best endeavours to ensure that the Information is correct and current at the time of publication but
takes no responsibility for any error, omission or defect therein. To the extent permitted by law, DET and its
employees, agents and consultants exclude all liability for any loss or damage (including indirect, special or
consequential loss or damage) arising from the use of, or reliance on, the Information whether or not caused by any
negligent act or omission. If any law prohibits the exclusion of such liability, DET limits its liability to the extent
permitted by law, to the re-supply of the Information.

Third party sites/links disclaimer: This document may contain website contains links to third party sites. DET is not
responsible for the condition or the content of those sites as they are not under DET's control. The link(s) are
provided solely for your convenience and do not indicate, expressly or impliedly, any endorsement of the site(s) or
the products or services provided there. You access those sites and use their products and services solely at your
own risk.
Contents
Getting Started .................................................................................................................................. i

About this unit .................................................................................................................................................................... i

Elements and performance criteria............................................................................................................................. i

Icon Legends....................................................................................................................................................................... ii

Topic 1 – Visual C# syntax ................................................................................................................ 1

Visual C# ............................................................................................................................................................................... 1

Creating your first program .......................................................................................................................................... 3

Arrays ...................................................................................................................................................................................14

Reading from a text file.................................................................................................................................................15

Writing to a text file ........................................................................................................................................................16

Summary ............................................................................................................................................................................19

Topic 2 - Object oriented principles .............................................................................................. 20

Object-oriented programming principles .............................................................................................................21

Abstraction ........................................................................................................................................................................21

Encapsulation ...................................................................................................................................................................23

Inheritance.........................................................................................................................................................................25

Polymorphism ..................................................................................................................................................................27

Composition .....................................................................................................................................................................28

Modularity .........................................................................................................................................................................31

Debugging code .............................................................................................................................................................32

Summary ............................................................................................................................................................................35

Topic 3 - An object-oriented programming project ..................................................................... 37

Documentation................................................................................................................................................................37

Aggregation ......................................................................................................................................................................39

Internal documentation ...............................................................................................................................................41

Code structure..................................................................................................................................................................41

Appropriate use of commenting ..............................................................................................................................42


Creating a solution ......................................................................................................................................................... 46

Referencing the language documentation .......................................................................................................... 48

Summary............................................................................................................................................................................ 49

Answers to selected activities ........................................................................................................ 50


Getting Started
About this unit
This unit describes the performance outcomes, skills and knowledge required to undertake
introductory programming tasks using an object-oriented programming language, including
tool usage, documentation, debugging, and testing techniques.

It applies to individuals who are programmers in a variety of fields and who are required to
produce simple programs in object-oriented languages.

No licensing, legislative or certification requirements apply to this unit at the time of


publication.

Elements and performance criteria


Elements define the essential outcomes of a unit of competency. The Performance Criteria
specify the level of performance required to demonstrate achievement of the Element. They
are also called Essential Outcomes.

Follow this link to find the essential outcomes needed to demonstrate competency in this
Unit: http://training.gov.au

i|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Icon Legends
Learning Activities

Learning activities are the tasks and exercises that assist you in gaining a
clear understanding of the content in this workbook. It is important for you
to undertake these activities, as they will enhance your learning.

Activities can be used to prepare you for assessments. Refer to the


assessments before you commence so that you are aware which activities
will assist you in completing your assessments.

Case Studies

Case studies help you to develop advanced analytical and problem-solving


skills; they allow you to explore possible options and/or solutions to
complex issues and situations and to subsequently apply this knowledge
and these newly acquired skills to your workplace and life.

Discussions/Live chat

Whether you discuss your learning in an online forum or in a face-to-face


environment discussions allow you to create and consolidate new
meaningful knowledge.

Readings (Required and suggested)

The required reading is referred to throughout this Learner Guide. You will
need the required text for readings and activities.

The suggested reading is quoted in the Learner Guide, however you do not
need a copy of this text to complete the learning. The suggested reading
provides supplementary information that may assist you in completing the
unit.

Reference

A reference will refer you to a piece of information that will assist you with
understanding the information in the Learner Guide or required text.
References may be in the required text, another textbook on the internet.

Self-check

A self-check is an activity that allows you to assess your own learning


progress. It is an opportunity to determine the levels of your learning and to
identify areas for improvement.

Work Flow

Shows a logical series of processes for completing tasks.

ii | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
iii | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 1 – Visual C# syntax
You will need Visual Studio installed (latest version).

Visual C#
The aim of this section is to learn the syntax of the C# (pronounced See-Sharp) language.

Like any other language, (spoken, written or computer) it has a set of rules that govern its use.
There are several constructs that are important to understand:

> Statements

> Blocks

> Functions

> Classes

1|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The first three of these will be treated in Topic 1.

LEARNING ACTIVITIES ACTIVITY 1

Creating a project

1 Open Visual studio

2 From the file menu choose - NewProject

3 In the dialog that opens click Visual C# in the left pane and Console application in the right
pane

4 Rename the project myFirstProgram in the Name box at the bottom - click OK

2|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
In the next screen, the defaults for the project are created:

The details of these is not important to these notes. However, every program must contain at least
one:

> namespace

> class

> static void Main[]

Static void Main[] is where the compiler will look for the first instructions to execute.

Creating your first program


Place the cursor to the right of the brace ( { ) in line 12. Press Enter.

Type the next two lines exactly as they appear:

Console.WriteLine("My first program");


Console.ReadLine();

You may have made use of Intellisense, which offers options to select while you type.

3|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Note how the code is indented to indicate to section to which it belongs.

Save the project using file save or Ctrl-s.

Click the green Start button at the top of the window

The program should then run as follows:

If not, then there is an error in your code! Revisit the above instructions looking for where you
went wrong. Be specifically mindful of issues like spaces or brackets that are in the wrong
place.

4|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Press enter to terminate the program – the window will then close.

Error Management

Go back to the code, delete the semi colon ( ;) at the end of line 13.

Intellisense will place a red wavy underline as your first defence against errors, much like
Microsoft Word does with spelling errors.

Ignore this error. Save your project and run it again.

A pop-up error will occur as follows and the output window will describe the error.

5|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 2

Modifying your program

Modify the program so that the output is:

Statements

These are pre-defined instructions in the C# language, each with their own purpose.

The end of a statement is indicated by a semi-colon (;)

In the Activity above:

Console.WriteLine("My first program");

Is a statement which is a call to a function, Writeline ().

Other types of statements include:

Declaration
int myNumber;

This tells the compiler to assign a space in memory for an integer named myNumber.

6|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is known as a variable.

When a program runs, the names of the variables created, are not important – they are only
important to programmers reading them.

Because of this, it is easier to read in context, descriptive names such as

incomeForWeekFour rather than w4.

In all examples and assessments, use this naming convention for all variables:

The first word of the name is lowercase (income)

Join all other words (with no spaces) each starting with an uppercase letter

(ForWeekFour)

This convention is known as lowerCamelCase naming.

Assignment
myNumber = 45;

This is a statement that assigns the value 45 to the variable.

Read this statement: “myNumber becomes 45”

LEARNING ACTIVITIES ACTIVITY 3

Using a variable

Create a new C# project named Variable

Enter the following lines in the Main[] procedure

The Main[] procedure is the first to be executed when a program loads

int myNumber;
myNumber = 45;
Console.WriteLine(myNumber);
Console.ReadLine();

This program

> declares an integer myNumber

7|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
> assigns the value 45 to myNumber

> writes the value of mynumber to the console

Save your project and run it.

Repeat for this code:

Console.WriteLine("Please type something and press enter");


string userValue;
userValue = Console.ReadLine();
Console.WriteLine("You typed:" + userValue);
DateTime myDate = DateTime.Now;
Console.WriteLine("The date and time is " + myDate);
Console.ReadLine();

This program:

> declares a string whatYouTyped

> writes a message to the console

> assigns the text you entered to the variable userValue

> joins the string “You typed” and the value of userValue

> writes the result to the console

> assigns the current date and time to a variable myDate

> joins the string “The date and time is “ to the variable myDate and writes it to the console

Other types of assignments include:

Calculations

weeklyPay = hoursWorked * payRate

function calls

result = myFunction(x,y) myFunction is a user-defined procedure.

Selection

There are two types:

> a selection between 2 options

> a selection among 3 or more options

8|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The IF statement

In the case of two alternatives, the IF statement is used.

IF (condition)

// Code to run if condition is true

else

// code to run if condition is false

Code following two forward slashes ( // ) will be ignored by the compiler.

It is used to add comments to show meaning in the code, for others to read.

LEARNING ACTIVITIES ACTIVITY 4

Making decisions

Consider this code segment:

string myTypedNumber; // number entered at keyboard


int myInteger; // value when entry is converted
Console.WriteLine("Please enter a whole number");
myTypedNumber = Console.ReadLine();
myInteger = Int32.Parse(myTypedNumber);
if (myInteger > 50)
{
Console.WriteLine("That's a big number");
}
else
{
Console.WriteLine("That's a small number");
}
Console.ReadLine();

9|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Create a new project and enter this code in the Main[ ] procedure

What happens if the entry is not a number?

The switch statement

This statement allows different code to be executed depending on a range of values.

switch (expression)
{
case value1:
// do something
break;
case value2:
// do something different
break;
case value3:

….
default:
// what to do if none of the others match
break;
}

You can include several cases against which the switch may match.

The default case will run if none of the others are matched

If you omit the default, then there made be no code executed!

Example

Console.WriteLine("Enter the first name of a computer guy");


string myString;
myString = Console.ReadLine();
switch (myString)
{
case "Bill":
Console.WriteLine("You mean Bill Gates");
break;
case "Steve":
Console.WriteLine("You mean Steve Jobs");
break;

10 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
default:
Console.WriteLine("I don't know who you mean");
break;
}
Console.ReadLine();

LEARNING ACTIVITIES ACTIVITY 5

Using a switch statement

Use a switch statement like the one above to determine if any of the following are entered:

“NSW”, “QLD”, “VIC”, “SA”, “WA”, “TAS”,”ACT”, “NT”

Use a default if any other value is entered.

Iterations (looping)

There are times when the same code needs to be run several times.

To avoid writing the same code repeatedly, a loop structure is used.

Two commonly used types are:

1 For loop

2 While loop

For loop

This is used when the number of repetitions is known.

For( i = 0; I < 10; i++)

This statement consists of 3 parts:

> an initial condition (i= 0)

> a condition which must be true (i < 10) otherwise to loop will end.

> what to do at the end of each loop (i++)

i++ is a short way of writing add 1 to i.

11 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Here is an example

Create a new project named forLoop.

Enter this code into the Main[ ] procedure:

int i;
for(i=0;i<10;i++)
{
Console.WriteLine(i);
}
Console.ReadLine();

Oops! We violated the lowerCamelCase rule!

This is typically the only time this is done- as a counter in a for loop.

While loop

This is used when the number of repetitions is unknown.

while (condition)
{
// do these things repeatedly until (condition) is false
}

If (condition) is false at the start, nothing will be done inside the block.

Example

Enter this code for a new project named whileLoop

Console.Write("Enter a string for me please :");


string myString;
myString = Console.ReadLine();
while (myString.Length > 0)
{
Console.WriteLine(myString);
myString = myString.Substring(0,myString.Length-1);
}
Console.ReadLine();

This program asks the user to enter a string of characters.

The while loop will then do this:

> write the value of the string on a new line

12 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This line

myString = myString.Substring(0,myString.Length-1);

will assign to myString all but the last character of the string.

(In other words, it will remove the last character)

The loop will then restart- test if the length is > 0 , write the value and reduce by 1 character.

This process continues until the string is empty (mystring.length > 0 will be false)

LEARNING ACTIVITIES ACTIVITY 6

Using a while loop

Start a new project named ‘Multiples’.

Write a list of the multiples of 7, up to 100.

An example using many ideas introduced:

The Fibonacci sequence has the property that any number is the sum of the two previous
numbers.

The first 2 numbers are 1 and 1. The sequence continues 2, 3, 5, 8.

List the first 15 members of this sequence.

Solution
int firstNumber = 1;
int secondNumber = 1;
int i;
int nextNumber;
Console.WriteLine("The Fibonacci sequence");
Console.WriteLine(firstNumber);
Console.WriteLine(secondNumber);
for(i=3;i<=15;i++)
{
// calculate the next number in the sequence
nextNumber = firstNumber + secondNumber;
Console.WriteLine(nextNumber);
// make the value of firstNumber the second number
firstNumber = secondNumber;
// make the secondNumber the one just calculated.

13 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
secondNumber= nextNumber;
}
Console.ReadLine();

The program depends on the rule that the next number is the sum of the previous two. After
calculating the next number, we then re-assign:

> the first number with the value of the second one,

> the second one with the value of the new number.

Create a new project named Fibonacci and run it.

Arrays
Arrays are a group of variables or objects of the same type. When it is necessary to use many
of them, it would be rather tedious to declare several variables such as:

> int a1

> int a2

> int a3 etc.

To declare an array use [ ] after the variable type e.g. int [ ] testScores will declare an array of
integers. If the number of objects is known use int[] testScores =new int[5].

Run this example as ArrayExample.

// find the average of a set of scores


int[] scores= {22, 38, 17, 85, 53};
int total = 0;
int i;
float average;
for(i=0;i<scores.Length;i++)
total+= scores[i];
average = total / scores.Length;
Console.WriteLine("The average of the scores is "+average);
Console.ReadLine();

The type of variable used is decimal, even though the number in the array are integers. This is
because the division operator ( / ) will give an integer result if the operands are integers,
which is not what we want in this case.

14 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The statement

total+= scores[i];

increases the value of total by the value of score[i];

This is like writing

total = total + scores[i];

Reading from a text file


Open a new project named Textfiles

In the Solution explorer window Right click the name Textfiles

Choose Add- Item.

In the new dialog - choose text file - rename this file Names.txt

In the properties box below under advanced

Change the copy to output directory to Copy if newer.

static void Main(string[] args)


{
StreamReader myReader = new StreamReader("Names.txt");
string consoleLine ="";
while (consoleLine != null )
{
consoleLine = myReader.ReadLine();
if (consoleLine != null)
Console.WriteLine(consoleLine);
}
Console.ReadLine();
}

Also of use is to split the string into an array based on a special character, in this case a space.

namespace splitStrings
{
class Program
{
static void Main()
{
string s = "four score and seven";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)

15 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
{
Console.WriteLine(word);
}
Console.ReadLine();
}
}
}

Then, if the items in the file are numbers we need other strategies:

static void Main()


{
string s = "80,72,45,12";
//
// Split string on commas.
// ... This will separate all the numbers.
//
string[] words = s.Split(',');
int myTotal = 0;
int value;
foreach (string word in words)
{
value = Convert.ToInt32(word);
myTotal = myTotal + value;
Console.WriteLine(word);
}
Console.WriteLine("Total is :" + myTotal);
Console.ReadLine();

Writing to a text file


Note the use of the using statement here.

You will need to change the path and filename to one on your system.

You must have write permission for this folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace writeTextfile
{
class Program
{
static void Main(string[] args)
{
string[] lines = { "My first line", "My second line", "My third
line", "My last line" };
StreamWriter file = new StreamWriter("c:\myfile.txt");

16 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
foreach (string line in lines)
{
file.WriteLine(line);
}

}
}

LEARNING ACTIVITIES ACTIVITY 7

Read from a text file

Show how you can read a file of personal details:

> name

> address

> phone number

Print the items one line at a time.

You will need to use a symbol other than a space in the file for splitting.

LEARNING ACTIVITIES ACTIVITY 8

Convert text to numbers

Create a text file so that each line consists of 3 numbers.

For each line print a statement if the numbers form a Pythagorean triad or not

(A Pythagorean triad occurs if a2 + b2 = c2)

e.g.

3 4 5 is a Pythagorean triad

7 8 9 is not a Pythagorean triad.

17 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
8 15 17

5 12 13

9 40 41 are other examples of Pythagorean triads.

LEARNING ACTIVITIES ACTIVITY 9

Writing to a file

Enter 3 words at the console and write them to a text file.

LEARNING ACTIVITIES ACTIVITY 10

Essential viewing

It is highly recommended that you watch this series of videos from learn visual studio.

www.learnvisualstudio.net

The relevant videos for this topic are 1 – 13.

Note that you may be asked to register to watch the videos. If this occurs please simply enter your
TAFE email address to proceed.

Another useful site is

www.dotnetperls.com

18 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Summary
This topic introduces the syntax of the C# language, using visual studio.

The features are:

> writing to the console

> assigning variables

> functions

> decisions

> loops

19 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 2 - Object oriented principles
Many computer programming languages are based on procedures.

A procedure is a set of instructions executed in a sequence, selection or a loop or iteration.


These ideas were seen in topic 1 as the basis of the C# language.

However, procedural languages have several drawbacks:

> They are entirely unstructured. It is difficult to follow valid compiled code.

> It is vulnerable. Changes to code, such as that on a website, can be made while
maintaining its validity. There is no means of detecting such a change.

> They are restricted to the types contained within them. For example, integers and strings.

While object-oriented programming does not eliminate these issues, it reduces their effects.

20 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Object-oriented programming principles
The six principles of object-oriented programming are the focus of this topic.

They are:

1 Abstraction

2 Encapsulation

3 Inheritance

4 Polymorphism

5 Composition

6 Modularity

Abstraction
An abstraction denotes the characteristics of an object that distinguishes it from all other
objects.

In C#, this is done by creating a class. In earlier examples, each program contained at least one
class.

Consider a user as an object. A user may have these properties:

> username

> password

> email address

In C#, this would appear as:

class User
{
public string username;
public string password;
public string email;

Just as integers are types of objects, this has created a new ‘type’ named user. It is often
referred to as a blueprint - it can be used to make many objects.

21 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 11

Creating a simple class

Create a new project named classExample and enter the following code:

static void Main(string[] args)


{
User myUser = new User();
myUser.username = "joel52";
myUser.password = "#SW@$%";
myUser.email = "joel2116@hotmail.com";
Console.WriteLine(myUser.username);
Console.WriteLine(myUser.password);
Console.WriteLine(myUser.email);
Console.ReadLine();

}
class User
{
public string username;
public string password;
public string email;

class user – contains the definition of what a User is:

User myUser = new User() sets aside space in memory for an object of type User.

At this point you need to gain further understanding about what a constructor is and what types of
constructors there are. A good source of this knowledge as relevant to C# is:

http://msdn.microsoft.com/en-us/library/ms173115.aspx

myUser.username = “joel52” assigns a value to the username property of myUser.

Similarly, the next two lines assign a password and email address.

At this stage, there are no functions for creating a new User object.

This is known as a constructor.

Here are two constructors for the user class:

public void User ()


{
// a new user with no properties will be created
}

22 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
public void User(string n,string p, string e)
{
username = n;
password = p;
email = e;
}

The first creates an empty User - the call is via the new User() statement.

The second allows properties to be added. The call will look like this:

User myUser = new User(“Bill”,”^&*sdf”,”bill@gmail.com)

C# will know which one to use since the signatures are different.

( ) indicates no parameters and (“Bill”,”^&*sdf”,”bill@gmail.com) shows 3 parameters.

It is possible to have others, perhaps username and password only.

Extend this code to create another user myOtherUser and print the properties of it in the same way
as the example.

Encapsulation
This is the principle that the structure of an object and its behaviour can be easily separated.
This can allow the use of an object without knowing how it is constructed.

This is analogous to using an electronic device, such as a mobile phone, without knowing how
the electronics work.

Classes contain definitions for two types of content:

1 The properties,

2 The processes that use those properties. These are also known as methods. In short, this
allows hiding away the properties of an object and only allowing external use of the
processes that use them.

Example

A rectangle has two properties – length and width. The rectangle has two processes getArea
that calculates the area and getPerimeter which calculates the perimeter.

23 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
A rectangle has two properties - length and width. The rectangle has two processes - getArea
that calculates the area and getPerimeter which calculates the perimeter.

static void Main(string[] args)


{
Rectangle myRectangle = new Rectangle(23.5, 8.6);
Console.WriteLine(myRectangle.getArea().ToString());
Console.WriteLine(myRectangle.getPerimeter().ToString());
Console.ReadLine();
}

class Rectangle
{
private double length;
private double width;

public Rectangle(double a, double b)


{
length = a;
width = b;
}

public double getArea()


{
return this.length * this.width;
}
public double getPerimeter()
{
return 2 * (this.length + this.width);
}
}

Here is an implementation of this Rectangle class.

Note the keywords public and private that occur here.

Any property or method that is designated public, is accessible from outside the class. Those
which are declared private are not.

A typical class definition will make properties private and processes or methods public.

This forces outside agencies to use the class in the manner that the developer determines.

It is also common to use methods in classes where properties are private, which set and return
the values of these properties.

e.g. getLength()
{
return length;
}

24 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
setLength( double myLength)
{
Length = myLength;
}

These are known as getter and setter methods.

Note also the use of Rectangle as a method in this class.

A method with the same name as a class is known as a constructor and is used to make a new
instance of the class or an object.

The toString() method converts a type to string, so it can be printed on the console.

To revisit the principle of encapsulation, a class outside this class, only needs to know how to
create a rectangle not of what it is composed.

Rectangle anotherRectangle = new Rectangle(30,40)

This will create a new rectangle - all that is needed is the ‘signature’ of the method.

A signature is the number and type of parameters to pass to the method – in this case 2
double precision numbers.

LEARNING ACTIVITIES ACTIVITY 12

Extend the Rectangle example to print the area and perimeter of two other rectangles.

Inheritance
This principle is based on the idea that objects are similar. Rather than duplicating code, the
properties of the parent object can be used while also specifying the properties of the child
that are different.

Use the Rectangle example.

The rectangle has properties length and width.

25 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
A square however, has only a length property.

Creating this class based on the previous class will mean that we can avoid re-writing lots of
code.

Add this class below the Rectangle class

class Square : Rectangle


{
public Square()
{

}
}

This indicates that the new class Square inherits from the base class Rectangle

All the properties and methods for square will be as for Rectangle

In the main [ ] block add:

Square mySquare = new Square();


Console.WriteLine(mySquare.getArea().ToString());
Console.WriteLine(mySquare.getPerimeter().ToString());

Run this code. You will get 0 and 0 for the values of the square since we have no way of
passing parameters to the square as yet.

We can do this: (replace the 3 lines above with these)

Rectangle myOtherRectangle = new Rectangle(15,15);


Console.WriteLine(myOtherRectangle.getArea().ToString());
Console.WriteLine(myOtherRectangle.getPerimeter().ToString());

This is just using the Rectangle and not the square

Try adding a new constructor for square:

public Square( double a)


{
length = a;
}

OOPS! A red underline. This is because the properties of the rectangle are private and can’t be
accessed outside the base class. The parameters could be changed length and width to
public, instead of private, but this would defeat the purpose of making them inaccessible to
other classes.

26 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Use setters and getters for this purpose.

Retype the main[ ] so that it looks like this:

Rectangle myRectangle = new Rectangle(23.5, 8.6);


Console.WriteLine(myRectangle.getArea().ToString());
Console.WriteLine(myRectangle.getPerimeter().ToString());
Square mySquare = new Square(15);
// Rectangle myOtherRectangle = new Rectangle(15,15);
Console.WriteLine(mySquare.getArea().ToString());
Console.WriteLine(mySquare.getPerimeter().ToString());
Console.ReadLine();

Run this code again - it works, but the problem is that squares have only one parameter so the
area and perimeter is using 0 for the width.

Polymorphism
This principle allows actions or methods to be changed to suit different situations. In practice,
this means changing the definition of a method in an inherited class.

The following is an example of polymorphism.

Add procedures so the square class looks like this:

class Square : Rectangle


{

public Square()
{

}
public Square( double a)
{
length = a;
}

public double getArea()


{
return length * length;
}

public double getPerimeter()


{
return 4 * length;
}
}

27 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Now when the program runs, the correct results are achieved. An advantage of this is when
we have a collection of parent types - shapes.

If we override each correct function Polymorphism will call the correct child method
automatically.

The methods getArea and getPerimeter have been overridden when the child object requires
them. Since the signature of the methods for a square are different, when they are called, the
correct method is used. The advantage here is that if other shapes, with other methods are
used, they too can override these methods.

LEARNING ACTIVITIES ACTIVITY 13

Overloading class methods

Add the method diagonal below to the Rectangle class and overload it for the square class.

public double diagonal()


{
return Math.Sqrt(length * length + width * width);
}

The purpose is to support multiple variations of the class with different arguments.

Composition
This is the principle that objects can be composed of other objects.

In particular classes may be made up of other classes. The destruction of the outer object does
not destroy the inner objects.

This is implemented in C#, by placing the inner class definition inside another class.

Consider a deck of cards. A deck is an object composed of 1 or more cards.

28 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Here is the code for such a program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeckOfCards
{
class Program
{
static void Main(string[] args)
{

Deck myDeck = new Deck();


myDeck.makeDeck();
myDeck.deal();
myDeck.showHand();
//Console.WriteLine(myDeck.deal());
Console.ReadLine();
}

class Deck
{

// A deck of 12 cards
Card[] allCards = new Card[12];

private Card temp;

private Card[] myHand = new Card[5];

public void makeDeck()


{
// instantiate the 12 cards
temp = new Card("QS");
allCards[0] = temp;
temp = new Card("KS");
allCards[1] = temp;
temp = new Card("AS");
allCards[2] = temp;
temp = new Card("QH");
allCards[3] = temp;
temp = new Card("KH");
allCards[4] = temp;
temp = new Card("AH");
allCards[5] = temp;
temp = new Card("QD");
allCards[6] = temp;
temp = new Card("KD");
allCards[7] = temp;
temp = new Card("AD");
allCards[8] = temp;
temp = new Card("QC");
allCards[9] = temp;
temp = new Card("KC");
allCards[10] = temp;
temp = new Card("AC");
allCards[11] = temp;
}

29 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
public void deal()
{
// deal 5 cards - listed on the console
int i;
int cardIndex;
Random myRandom = new Random(1);
bool found;
string hand ="";
for (i = 0; i < 5; i++)
{
found = false;
while (!found)
{
// select a card for the hand
cardIndex = myRandom.Next(0, 11);
// Console.WriteLine(cardIndex);
// if it's already in the hand, don't add it
if (!hand.Contains(allCards[cardIndex].getCard()))
{
// add the card to the hand
myHand[i] = allCards[cardIndex];
hand = hand + allCards[cardIndex].getCard();
found = true;
}
}
}
}
public void showHand()
{
int i;
Console.WriteLine("This is my hand");
for (i = 0; i < 5; i++)
{
Console.WriteLine(myHand[i].getCard());
}
Console.ReadLine();
}

class Card
{
private string cardValue;

public Card(string c)
{
cardValue = c;
}

public string show(string c)


{
return c;

public void setCard(string c)


{
cardValue = c;
}

public string getCard()


{

30 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
return cardValue;
}
}
}

}
}

Notice how the card is defined within the Deck class.

You will need to change the Random value in order that a different set of cards is dealt.

Modularity
This principle refers to the fact that program code is contained in separate modules (classes).
This allows for easier maintenance of code, as problems or bugs can usually be located within
a specific module. Another advantage is the use of the Microsoft base class library. These are
class definitions that Microsoft make available to developers, thus preventing the need to
develop such classes “from scratch”.

Modularity considers how all code run in either in the Main[ ] module or within a class, using
the properties of the class.

LEARNING ACTIVITIES ACTIVITY 14

Modularity

A car class has properties of name and speed.

There are two functions:

1 Accelerate, which increases the speed by 10, and brake, which decreases the speed by 10.

2 Instantiate a car object with car(“Volvo”, 40)

Use keyboard inputs “a” and “b” for the functions.

If any other entry is made, no change is made to the speed.

End the program when the speed reaches 0.

31 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Debugging code
It has been shown previously that Visual studio supports debugging of code in several ways.

1 Intellisense syntax checking.

It may have been clear already that Intellisense is watching what you type and that errors are
reported with red underlining - even before lines of code are complete.

2 Intellisense drop down options.

Often Intellisense will anticipate what is coming next.

This is true about functions, such as overloaded methods. Intellisense will provide a drop
down menu from which to select.

> Debug run-time messages.

When you execute a program in the debugger, run time errors will be reported in a pop up.

> Debug message window

In order that messages are retained, the same message will appear in the message window
after the pop up is cleared from the screen.

LEARNING ACTIVITIES ACTIVITY 15

Using the debugger

Revisit the program whileloop from Topic 1.

static void Main(string[] args)


{
Console.Write("enter a string for me please :");
string myString;
myString = Console.ReadLine();
while (myString.Length > 0)
{
Console.WriteLine(myString);
myString = myString.Substring(0,myString.Length-1);
}
Console.ReadLine();
}

32 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Change the line:

string myString;
to read

string mySring;

(that is, delete the ‘t’)

This sets off Intellisense as myString is no longer defined. Each occurrence will generate a red
underline.

Note also the red underline – hover over it with the cursor and a list of options will be available to
you.

Save the program and run it.

The pop-up will only suggest an error, not give the details. The debug window will report
errors and the lines on which they occur.

33 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Stepping through a program

Replace the error created above.

Click on the extreme left of the edit window next to line 18 – a red circle appears.

This sets a breakpoint in the program. It can be used to examine the actions of the program
while it is running.

Running the program will stop execution of it at line 18.

Click the green run button to continue the program. Because the breakpoint is inside the
while loop, it will stop each time it reaches line 18.

Click locals in the error list window at the lower left to see the value of local variables.

Local variable list showing the value of myString “ABCD” at the breakpoint.

34 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is useful in finding logic errors in a program.

Click the red circle to remove the breakpoint.

Summary
A class is a blueprint for an object. It is created to allow program design to reflect the design
need. Objects are instances from classes.

The six principles of object oriented programming are:

1 Abstraction - using a class to define the objects required.

2 Encapsulation - containing all the information about an object within the class.

3 Inheritance - the ability to create subclasses with similar properties

4 Polymorphism - the overloading of a method with another

5 Composition - the creation of a class within another class.

6 Modularity - containing all code within appropriate classes

Visual Studio gives many chances to catch program errors:

> Red underlines to show syntax errors

> Run time pop-ups

> Debug messages

LEARNING ACTIVITIES ACTIVITY 16

Recommended viewing

Watch this series of videos from learn visual studio.

35 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
http://www.learnvisualstudio.net/free/c-training/

The relevant videos for this topic are 14 – 18.

36 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 3 - An object-oriented
programming project
Documentation
Documenting a programming project is a continuous process. At each stage of the project,
documents will support the ideas collected.

Project requirements

Initially, this will consist of several statements listing what the program will need to do. This is
often stated as a description of what the user will be entering and what the output will be.

Example: Gold and diamonds

37 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is a variation on the mastermind game. The program chooses a four digit number with
no repeated digits and the user has 8 turns in which to guess it.

After each turn, the program responds with a clue about each guess. Each digit in a guess
which occurs in the same position as the program’s number is called a gold, common digits
that occur otherwise are called diamonds.

For example, suppose the program’s number is 2307.

A guess of 5380 would result in 1 gold and 1 diamond.

The 3 is in the correct column (gold) but the 0 is present but not in the correct column
(diamond).

A return of 4 ‘golds’ is then the correct number. The user has a maximum of 8 turns to
get the number correct.

Analysis & design

Class diagrams are used to indicate the principles that will occur in the project.

A class is represented by a rectangle with 3 sections as follows:

Title

Attributes

Methods

Rectangle

length: double
width: double From Topic 2
getArea()
getPerimeter

38 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Inheritance is shown by connection with an arrow as follows:

Rectangle

length: integer
width: integer
getArea()
getPerimeter

Square

length: double

getArea()
getPerimeter

Aggregation
This is a relationship in which one class is composed of several instances of another class.

For example:

Car Wheel
-memberName -memberName
-memberName -memberName

This indicates that a car object (an instance of the car class) is composed of 1 or more wheel
objects (instances of the wheel class)

Returning to the game in the requirements section above, the following observations are
made.

> A game consists of many numbers- suggesting aggregation.

> A method of the number class will be to calculate what the result is.

> The games class will need members:

> over - a Boolean storing the status of the game

> result - a double returning the result of the guess

> guesses - an int counting how many guesses have been made

> Two instances of numbers the program’s number and the current guess

39 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
> The number class will need members.

> Guess - a string storing the number

> Value - a string that stores the created number

> an empty constructor to create a new guess for the user to enter

> an overriding constructor that creates the program’s number

> a method to validate the number the user entered.

> a method to calculate the result

A class diagram for this program is as follows:

Game
myNumber
int guesses;
bool over; -string myguess
double result; myNumber();
myNumber answer; myNumber(int type)
myNumber thisGuess; validate();
Play() reply();

This diagram only shows details at the class level. There will be other variables created within
the scope of the named methods.

LEARNING ACTIVITIES ACTIVITY 17

Modelling solutions

Create simple class diagrams to show:

1 A spider is an animal. A spider has 8 legs.

2 An insect is an animal. A bee is an insect.

40 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 18

Class diagrams

Consider an electric jug as an instance of a class.

> What member values would it have?

> What member methods would act on these values?

> Construct a class diagram with this information.

Internal documentation
Programming standards require that any single program has the following features:

> it has developer contact details

> the structure of the code is easy to follow

> comments are included to explain to other developers what is being done

> suitable use of variable names

The first few lines of code should include the following:

> developer name

> date of development

> version of the program

> platform in which it is written

> acknowledgments of code sourced from elsewhere

Code structure
Visual studio is helpful in that it will indent code as each new scope { } is created.

The recommended indent is 3 characters in each new scope.

41 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Appropriate use of commenting
The best programming code makes sparing use of code!

Reasons comments are used include:

> showing when a point in the program has been reached

> explaining complex sections of code

For example:

// this point is reached after the whole file has been read

// this section swaps the values of firstRecord and secondRecord

The gold and diamonds game continues with a coded solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Author John Doe
// 6/11/2013
// Version 2.0
// created in C# using Visual studio 2013

namespace GoldDiamonds
{
class Program
{
static void Main(string[] args)
{
// main consists of a single call to the game class
game myGame = new game();
myGame.play();
}

class game
{
myNumber answer = new myNumber(0); // number the user tries to
guess
myNumber myTurn = new myNumber(); // current turn of the user
bool over = false; // flag to indicate whether another turn is
required
int maxGuesses = 8; // fixed number of guessed allowed
int guesses = 0; //
double result; // decimal value of the guess' result
public void play()
{
// main method of the program
// the program ends if 8 guesses are made or the number is
gueesed correctly
while (!over && guesses < maxGuesses)
{

42 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Console.Write("please enter guess " + (guesses + 1)+ " ");
myTurn.myGuess = Console.ReadLine();
if (!myTurn.validate())
{
Console.WriteLine("That guess is not valid");
}
else
{
result = myTurn.reply(answer);
show(result);
guesses++;
if (result == 4 )
{
Console.WriteLine("you win!");
over = true;
}
if (guesses == 8 )
{
over = true;
Console.WriteLine("No the number was " + answer);
}
}

}
Console.ReadLine();
}
public void show(double res)
{
string myResult = res.ToString();

string[] scores = myResult.Split('.');


if (scores.Length == 1) scores[1] = "0";
Console.WriteLine(scores[0] + " golds ," + scores[1] + "
diamonds");
}

}
class myNumber
{
public string myGuess;
public myNumber ()
{

}
public myNumber(int type)
{
int i;
string myString = "";
string myChar;
int value;
bool found; // flag if a unique digit is chosen.
Random myRandom = new Random();// uses the system Random
Class
for(i=0;i<4;i++)
{
found = false;
// this looks for a digit not already used.
while (!found)
{
value = myRandom.Next(48,57);
myChar = char.ConvertFromUtf32(value);
if (!myString.Contains(myChar))

43 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
{
myString = myString + myChar;
found = true;
}
}
}
myGuess = myString;
}
public bool validate()
{
// validates the user input
bool valid = true; // flag the outcome
int i=0;
string mydigits = "0123456789";
string list ="";
if (!(myGuess.Length == 4)) valid = false;
while (i<4 && valid)
{
// each digit must in mydigits and not be already in
the string
if (mydigits.Contains(myGuess[i] ) &&
!list.Contains(myGuess[i] ))
{
list = list + myGuess[i];
}
else
{
valid = false;
}
i++;
}
return valid;
}
public double reply(myNumber n)
{
// calculate the number of gold and diamonds
string test1 = myGuess;
string test2 = n.myGuess;
int i;
double diamonds = 0;
double golds=0;
// count the golds and diamonds
for(i=0;i<4;i++)
{
if (test1[i] == test2[i]) golds++;
if (test2.Contains(test1[i])) diamonds++;
}
// this loop will count golds as diamonds
// this calculation allows one return value
// e.g. 1.2 is 1 gold and 2 diamonds.
return golds + (diamonds-golds) / 10;

}
}
}

44 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 19

Use of comments - 1

Consider the commenting in the gold and diamonds game. Is there any area where further
comments would help?

LEARNING ACTIVITIES ACTIVITY 20

Use of comments - 2

Suppose you have written the following program:

namespace commenting
{
class Program
{
static void Main(string[] args)
{
int i;
int j;
int[] myList = { 3, 11, 6 };
for(i=0;i < myList.Length;i++)
{
if (myList[i] < 10 ) Console.WriteLine (myList[i] + " has 1
digit") ;
else
if(myList[i] < 100 ) Console.WriteLine (myList[i] + " has 2
digits");
else Console.Write (myList[i] + " has more than 2 digits");
}
Console.ReadLine();
}

}
}

Edit the program to include suitable comments as outlined above.

45 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Testing code

Testing will mean that all requirements of the program are tested.

In the gold and diamonds example it will be necessary to check that:

> guesses only contain digits

> guesses are only four digits

> no 2 digits are allowed equal in a guess

> only 8 guesses are allowed

> that the final feedback is correct – you will need to test for a win and a loss

LEARNING ACTIVITIES ACTIVITY 21

Testing

Use the guidelines above to completely test the gold and diamonds game.

Can you find any errors in the code - contrary to the requirements?

Creating a solution
To finish these notes, consider a solution created from the requirements statement and the
class diagram provided below.

READINGS RECOMMENDED 1

It may be necessary to refer to documentation for the C# language.

http://msdn.microsoft.com/en-us/library/kx37x362.aspx

The user must enter a string from the keyboard.

46 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The word is to be written to the console with the following replacements:

a-@

e-3

i-1

o-0

u-%

The program repeats this section.

When the user enters an empty string, the program ends.

Operator Entry
bool over String myString
string temp analyse()
entry myEntry
search()

namespace encode
{
class Program
{
static void Main(string[] args)
{
operation myOperation = new operation();
myOperation.search();
}
class operation
{
bool over = false;
String temp;
entry myEntry = new entry();

public void search()


{
while (!over)
{
Console.Write("please enter a string of characters: ");
temp = Console.ReadLine();
myEntry.text = temp;
if (myEntry.text == "") over = true;
else myEntry.analyse();
Console.WriteLine(myEntry.text);
}
Console.ReadLine();
}

47 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
class entry
{
public String text;

public void analyse()


{
int i;
String temp;
temp = "";
for (i = 0; i < text.Length; i++)
{
switch (text.Substring(i, 1))
{

case "a":
temp = temp + "@";
break;
case "e":
temp = temp + "3";
break;
case "i":
temp = temp + "1";
break;
case "o":
temp = temp + "0";
break;
case "u":
temp = temp + "%";
break;
default:
temp = temp + text.Substring(i, 1);
break;
}

}
text = temp;
}

}
}
}
}

What tests are required for this program?

Referencing the language documentation


There will be times when some language features are required to complete coding.

Use the Microsoft developer network for this purpose.

http://msdn.microsoft.com/en-au/

http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx

48 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This site has references for the C# language

http://www.dofactory.com/reference/csharp-coding-standards.aspx

Summary
Documentation of programs includes two main objectives:

1 Identifying the developer and the context in which the program was written,

2 Making the program readable by other developers

These are met by using:

> code at the top of the program introducing the developer

> comments to explain logic

Class diagrams are the result of program design. They give developers ideas about what
objects will be used in the program. They show how the objects interact.

Testing of software is done to determine if errors occur.

It is important to test all outcomes of a program.

A coded program solution is the result of a requirements statement - and design


documentation and appropriate testing.

49 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Answers to selected activities
Answers are not provided for all activities. Some activities are reflective or are best answered
from your own research or point of view. In these cases you should discuss your answers with
your facilitator/facilitator and other learners wherever possible.

Activity 1 – Creating a project

Activity 17 – Modelling solutions

17.1

Animal

Spider Leg

17.2

50 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Animal

Insect

Bee

Activity 18 – Class diagrams

Electric Jug
bool powered
bool boiled
double waterLevel
boil()
fill()

These are of course subjective - are there any others?

Activity 19 – Use of comments - 1

Any area of the program that you need further clarification about needs more comments.

Activity 20 – Use of comments - 2

Test that each of the letters a, e , i , o and u are replaced correctly

Test that the program ends.

51 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow