Variables Data Types and Assignment

In the first lecture we introduced the idea of classes and objects.

An object is a word in our code that represents the functions in a class. Once we have an instance of an object we may access the methods and properties defined in the class.

Properties allow us to change or find out about some aspect of the data. Methods allow us to perform some action on the data.

There are lots of different objects within the computer system all allowing us to control the data in different ways.

The Text Box

The text box is a control you will have used lots and lots of times without thinking about it. In the lab this week you will create several text boxes as you put together your presentation layer.

The text box is an object that allows us to accept data from the keyboard and also display data to the user.

The text box is a screen based object used for input and output.

System Architecture

Not only do we split the system into layers.

We may also split layers into smaller layers.

The Structure of the Presentation Layer

There are in fact two parts to the presentation layer in our architecture.

The Interface the part the user sees and interacts with

Presentation Layer Code the code that makes the interface work

When a person has entered a value into the web form they will click the button on the form triggering an event.

Events

Events are things that happen to the form and controls such as “click”.

What we do is we associate functions with events. An event handler function is triggered whenever an event is triggered.

If we were to double click on the “Yes” button in the above example we would be able to see the event handler for the button.

Interface v RAM – Using the Right Tool for the Right Job

To illustrate the point here have a go in pairs at seeing who is able to count the fastest. One person count in their head from 1 to 50, the other person count from 1 to 50 writing on paper.

As you would probably expect the person counting in their head will win every time. Why? Because they are not just counting, they have the extra overhead of writing the numbers down.

The same is true of interface controls versus RAM.

Because the interface control has a visual component it is slower that using the RAM in the computer. If we copy the data from the interface and place it into the RAM our programs are going to be a lot faster.

The Assignment Operator

One tool for copying data around the system is the assignment operator.

=

This is possible the most important part of the language to fully understand.

It works by copying data from one object to another.

The text box screen object has a property called “Text”. So what do you think the following line of code will do?

txtMessage.Text = “Hello world”;

The answer is that it would display the message “Hello world” on the web page.

The assignment operator copies data from right to left

Destination = Source

So

txtMessage.Text = “Hello world”;

Copies the data “Hello world” to the text property of the text box.

Understanding the RAM

Inside your computer are various bits of computer technology. You have your CD-ROMs, your Hard Disk Drives etc. One component inside your computer is RAM (Random Access Memory). This is the part of the computer where your computer “remembers” data for short periods of time.

Like everything else in the language RAM is controlled by means of objects. The objects that allow us to control the RAM are called variables.

A simple calculation on paper, for example…

3=1+2

Is quite easy for humans to work out but for a computer this is quite a complex task.

A computer needs to set aside three areas of RAM.

One for the result

Two for the other two numbers

It will also perform the calculation in binary for example…

00000011=00000001 + 00000010

RAM inside a computer is in fact very complicated. Variables give us a nice simple system for controlling the RAM so we as programmers don’t need to get involved in thinking about memory and binary.

Declaring Variables

Look at the following lines of code…

//declare a variable to store the error message

string ErrMsg;

//declare a variable to store the title of the swap

string OfferTitle;

//declare a variable to store the description of the swap

string Description;

//declare a variable to store the unique identifier of the swap

Int32 SwapNo;

//declare a variable to demonstrate that names are case sensitive

Int32 swapNo;

//declare a variable to store the email address of the current user

string EMail;

//declare a variable to store the username of the current user

string UserName;

These lines of code declare variables. Each line tells the computer to create a variable allowing us to control a section of the RAM.

It is good practice to place variable declarations at the start of a function.

This makes the declarations easier to find and also reduces the problem of trying to use a variable before we use it.

Variables must also be declared before we may use them.

//declare a variable to store the age

int MyAge;

//assign the age with 24

MyAge = 24;


Is good!

//assign the age with 24

MyAge = 24;

//declare a variable to store the age

int MyAge;

Is bad! We must declare a variable before we try to use it not after.

To tell the computer to declare a variable in C# we start by specifying what sort of data it will store, the data type.

//declare a variable to store the error message

string ErrMsg;

//declare a variable to store the title of the swap

string OfferTitle;

//declare a variable to store the description of the swap

string Description;

//declare a variable to store the unique identifier of the swap

Int32 SwapNo;

//declare a variable to demonstrate that names are case sensitive

Int32 swapNo;

//declare a variable to store the email address of the current user

string EMail;

//declare a variable to store the username of the current user

string UserName;

The above section of code declares seven variables.

Naming Variables

In the computer a location in memory is given a numeric address, e.g. 65534.

We as human beings are not very good at remembering numbers like this, so when we declare a variable in memory we give the variable a name.

The seven variables declared above have the following names…

ErrMsg

OfferTitle

Description

SwapNo

swapNo

EMail

UserName

The computer will allocate a section of memory for each variable and give it the name we have specified.

You may think of the RAM as a series of boxes. In the above code we have asked the computer to set aside seven boxes of RAM with the following names…

ErrMsg / OfferTitle / Description / SwapNo / swapNo / EMail / UserName

Notice a few things about the names of the variables...

·  Variable names are case sensitive (swapNo & SwapNo are two different variables)

·  We do not have any spaces in the variable names

·  The variable names use pascal case, e.g. OfferTitle not offertitle

·  The names are meaningful

Data Types

Notice also in declaring variables we give them a data type, e.g.

string

The data type sets the rules on what kind of data a variable is allowed to store.

In the following code…

//declare a variable to store the description of the swap

string Description;

The variable description is given a data type of string. A string variable is allowed to store any alphanumeric value A-Z,a-z,0-9 etc..

In the following code…

//declare a variable to store the unique identifier of the swap

Int32 SwapNo;

The variable SwapNo is given a data type of Int32. The Int is short for Integer. An integer is a whole number in the range from -2,147,483,648 to 2,147,483,647.

The 32 indicates the number of BITS in RAM allocated to the variable.

The more bits we allocate the bigger the range of numbers we may store.

Int16 -32768 to +32787

Int32 -2,147,483684 to +2,147,483683

Int64 -9223372036854775808 to +9223372036854775807

Using more bits however uses more memory.

(The data type int on its own is the same as Int32)

Specifying a data type creates a rule on what kind of data the boxes may contain…

string
(Text only) / string
(Text only) / string
(Text only) / Int32
(Whole numbers only) / Int32
(Whole numbers only) / string
(Text only) / string
(Text only)
ErrMsg / OfferTitle / Description / SwapNo / Userno / EMail / UserName

Variable Errors

A Variable Declaration is Missing

What happens if we remove a variable declaration?

What if we change this example by deleting one of the declarations?

Here we have commented out the declaration for “MyAge”.

If we try to use a variable that has not been declared Visual Studio will underline it in red.

The red underlining tells us that there is a problem. Hold the mouse pointer over the underlined text and an error message will appear…

One very important skill in programming is being able to read and understand error messages. You will make lots of errors as you learn to program, even experienced programmers get things wrong.

You need to accept this and learn to deal with errors in a positive way.

Compilation with no Variable Declaration

What happens if we ignore the error and run the program anyway?

If you run a program with an error you should see the following error message…

THE ANSWER TO THIS QUESTION IS ALWAYS

NO!

If you press yes Visual Studio will simply run the last working version of the program, not the version you have in front of you.

Press “No” and let Visual Studio show you what the error was.

You should see an error list…

Double click on the top entry in the error list…

1 The name ‘MyAge’ does not exist etc...

You will be taken to the line of code where the error has been generated…

Error messages are there to help you – don’t just ignore them and hope they will go away!

Mismatched Variable Names

What happens if we change the names of one of the declared variables?

Imagine we have a variable called SwapNo

//var to store the unique identifier of the swap

int SwapNo;

We change it to..

//var to store the unique identifier of the swap

int SwapNumber;

Again you would see a similar error to the one above…

Not only must a variable have a declaration before we may use it, a variable’s name must be the same when it is declared and when it is used.

Selecting the Wrong Data Type

What if we do this?

Why is the text underlined in red?

The problem is that we have declared the variable like so...

//declare a variable to store the description

int Description;

With an Integer data type!

We cannot assign an integer variable with text.

C# is what is called a strongly typed language.

What this means is that it is fussy about what data may be transferred between data types.

Take a look at the following lines of code..

//declare a variable in ram to store the data from the interface

Int32 AddressNo;

//use the assignment operator to copy the data from the interface to the ram converting the data type

AddressNo = Convert.ToInt32(txtAddressNo.Text);

The problem here is that the Text property of the text box txtAddressNo is a string data type (text). The variable AddressNo is type int

Assigning Literal Constants

In the examples above we have assigned values from one place in the system to another, e.g. from a text box to a variable.

There are times when we simply want to give a variable a value, often to initialise it.

A literal constant is a set value specified by you the programmer.

Take a look at the following…

Int32 DaysLeft;

DaysLeft = 365;

This declares a variable called DaysLeft with a data type of Integer.

The second line initialises it with a value of 365.

This could also be written like so…

Int32 DaysLeft = 365;

Look also at the following…

string PNumber;

PNumber = "Pxxxxxxxx";

In this case we are declaring a variable called PNumber with a string data type. In the second line we assign it a value of Pxxxxxxxx

Notice the speech marks surrounding the string value.

These speech marks are delimiters to indicate when the string we want to assign begins and when it ends. (It is more obvious with a number when it starts and ends.)

Performing Simple Calculations

Take a look at the following code...

Int32 FirstNumber;

Int32 SecondNumber;

Int32 Result;

FirstNumber = 20;

SecondNumber = 30;

Result = FirstNumber + SecondNumber;

What is happening here and what will be the value of Result?

The line of code...

Result = FirstNumber + SecondNumber;

Is an example of a simple calculation. The + (addition operator) is used to add the value of FirstNumber to SecondNumber.

Rounding Errors

Consider the following code…

Int32 MyVariable;

MyVariable =Convert.ToInt32(12.2);

What do you think will happen?

The Integer data type may only store whole numbers however here we are trying to store the value 12.2. The decimal value will be rounded.

To get around this we need to use a decimal data type…

decimal MyVariable;

MyVariable = 12.2m;

Notice how we identify it as a decimal number by placing an ‘m’ at the end. This is similar to how we identify a string by enclosing in quotes.

Overflow Errors