You are on page 1of 46

Web Design and Development – Program #1423 PROG8330

Advanced Programming
with .NET

Introduction to C# - Lecture 2

March 23, 2024


Introduction to C# - Creating Programs
Last lecture we had a good look at the basics of what makes C#
work. Now we’ll taking a closer look at some of the other
constructs available in the language…

Starting on Page 48
Methods
We have already come across the methods Main, WriteLine and
ReadLine. Main is the method we write which is where our
program starts.
WriteLine and ReadLine were provided by the creators of C# to
give us a way of displaying text and reading information from
the user.
Methods.
This is what methods are all about. Your programs will contain
methods that you create to solve parts of the problem and they
will also use methods that have been provided by other people.
Methods..
Up until now all our programs have been in a single method.
The method is the block of code which follows the main part in
our program.
Methods…
However, C# lets us create other methods which are used when
our program runs. Methods give us two new weapons:
• We can use methods to let us re-use a piece of code which
we have written.
• We can also use methods to break down a large task into a
number of smaller ones.
Try: Code Sample 09 Simple Method
Parameters
At this point methods are useful because they let us use the
same block of statements at many points in the program.
However, they become more useful if we allow them to have
parameters.
Parameters.
A parameter is a means of passing a value into a method call.
The method is given the data to work on. As an example,
consider the code in:
Code Sample 10 Method with parameters
Return values
A method can also return a value to the caller. You have already
used this feature, the methods ReadLine and Parse both return
results that we have used in our programs. Now try the code in:
Code Sample 11 Method return with plus
Return values.
The method sillyReturnPlus takes the value of the parameter
and returns it plus one.
The value that a method returns can be used anywhere in a
program where a variable of that type could be used, in other
words a call of sillyReturnPlus can take the place of an integer.
Return values..
See if you can work out what this code would display:

res = sillyReturnPlus (5) + sillyReturnPlus (7) + 1;


Console.WriteLine ( "res is : " + res ) ;
Arguments and Parameters
When you read about C# you will find the words parameter and
argument used interchangeably.
This is actually not quite right.
Arguments and Parameters.
Understanding the difference will make C# documentation and
error messages seem more sensible and might even give you a
feeling of superiority over lessor programmers who don’t know
the truth.
Arguments and Parameters..
A parameter is the special kind of variable that is defined in the
method header and used inside that method to represent the
value that was fed into the method call.
An argument is the value that is supplied to the method when it
is called.
A Useful Method
Review page 50 and code example:
Code Sample 12 Using a Useful Method.
Look in the code at how the readValue method is above the
Main method. Then see how readValue is being called in Main
while passing in the related arguments.
Named Arguments
When you create a method which has parameters you tell the
compiler the name and type of each parameter in turn.
If you want to make method calls and not have to worry about
the order of the arguments you can name each one:

x = readValue(low:25, high:100, prompt: "Enter your age");

Page 52
Named Arguments.
Now the compiler is using the name of each argument, rather
than its position in the list.
This has the useful side effect of making it much clearer to
someone reading your code the exact meaning of each
argument value.
Optional Arguments
Sometimes the value of an argument might have a sensible
default value.
For example, if we just wanted the readValue to fetch a value
from the user and not display a prompt we could do this by
providing an empty string:
x = readValue(low:25, high:100, prompt: "");
Optional Arguments.
However, this is a bit messy.
Instead we can change the definition of the method to give a
default value for the prompt parameter:
Optional Arguments..
static double readValue (
double low, // lowest allowed value
double high, // highest allowed value
string prompt = "", // optional prompt for the user
)
{
...
}
Optional Arguments…
We can now call the method and leave the prompt out if we like:
x = readValue(25, 100);
When the method runs the prompt will be set to an empty string
if the user doesn’t provide a value.
Optional Arguments….
Note that I’ve had to rearrange the order of the parameters so
that the prompt is the last parameter.
Optional parameters must be provided after all the required
ones.
Parameter Passing By Value
By default, all parameters are passed by value in C#. This
simply takes a copy of the value of the parameter for use in the
method.
Pass by value is very safe, because nothing the method does
can affect variables in the code which calls it. However, it is a
limitation when we want to create a method which returns more
than one value.
Parameter Passing By Reference
Fortunately C# provides a way that, rather than sending the
value of a variable into a method, a reference to that variable is
supplied instead.
Inside the method, rather than using the value of the variable
the reference is used to get the actual variable itself.
Parameter Passing By
Reference.
Effectively the thing that is passed into the method is the
position or address of the variable in memory, rather than the
content of the variable.
In this case the method call can make changes to the content of
the referenced variable.
Parameter Passing By
Reference..
Note that C# is careful about when a parameter is a reference.
You have to put the word ref in the method heading and also in
the call of the method:
static void addOneToRefParam ( ref int i )
{
i = i + 1; Console.WriteLine ( "i is : " + i ) ;
}
Passing Parameter values as "out" references
When you pass a parameter as a reference you are giving the
method complete control of it.
Sometimes you don't want this. Instead you want to just allow
the method to change the variable.
Passing Parameter values as "out" references.
This is the case when we want to read in the name and age of a
user. The original value of the parameters is of no interest to the
method.
Instead it just wants to deliver results to them. In this case I can
replace the ref with the keyword out:
Passing Parameter values as "out" references..
static void readPerson ( out string name, out int age )
{
name = readString ( "Enter your name : " ) ;
age = readInt ( "Enter your age : ", 0, 100 ) ;
}
Passing Parameter values as "out" references…
I can call readPerson as follows:
string name ;
int age ;
readPerson ( out name, out age ) ;
Note that I must use the out keyword in the call of the method
as well.
For Your Review
Additional reading should be considered:
• Method Libraries: Page 56
• Variables and Scope: Page 58 - 61
Arrays
C# provides us with a thing called an array. An array allows us
to declare a whole row of a particular kind of box.
We can then use things called subscripts to indicate which box
in the row that we want to use.
Consider the following:

Page 61
Arrays.
Arrays..
The int [ ] scores part tells the compiler that we want to create
an array variable. You can think of this as a tag which can be
made to refer to a given array.
The bit which makes the array itself is the new int [11].

Try: Code Sample 16 Using an Array


Creating a Two Dimensional Array
However, sometimes we want to hold more than just a row.
Sometimes we want a grid. We can do this by creating a two
dimensional array.
You can think of this as an "array of arrays" if you like (but only
if this doesn't make your head hurt).
Creating a Two Dimensional Array.
For example, to hold the board for a game of noughts and
crosses (tic tac toe) we could use:
int [,] board = new int [3,3];
board [1,1] = 1;
For Your Review.
Additional reading should be considered:
• Arrays and Lookup Tables: Pages 65 - 66
• More than Two Dimensions: Page 66
Exceptions and the Parse method
Parse is the method we use to convert strings of text into
numeric values.
int age = int.Parse(ageString);
The above statement uses int.Parse to convert the string in
ageString into an integer result which is then stored in the
variable age.
Exceptions and the Parse method.
This works well, but it is not without its limitations. The problem
with Parse is that if you give it a string that contains invalid text
it doesn’t know what to do with it.
Parse solves its problems by throwing an exception for another
part of the program to catch.
Catching Exceptions
We can make our programs deal with invalid text input to Parse
by adding code that will catch the exceptions that Parse throws
and try to fix the problem.
In programming terms this is called “dynamic error handling” in
that our program is responding to an error when it occurs.
Catching Exceptions.
To do this we have to use a new C# construction, the
try – catch clause.
The try keyword is followed by a block of code. After the block
of code comes the catch clause. If any of the statements
following the try throws an exception the program runs the code
in the catch clause to handle this error.

Try: Code Sample 17 Simple Exception Catching


The Exception Object
When I pass a problem up to my boss I will hand over a note
that describes it. Exceptions work in the same way. An
exception is a type of object that contains details of a problem
that has occurred.
When Parse fails it creates an exception object that describes
the bad thing that has just happened (in this case input string
not in the correct format).
Try: Code Sample 18 Using the Exception message
For Your Review..
Additional reading should be considered:
• Exception Nesting: Pages 68 - 69
• Adding a Finally Clause: Pages 69 – 70
• Throwing an Exception: Page 70
• The Switch Construction: Pages 70 – 73
o Special note on Multiple Cases: Pages 72 – 73

• Using Files: Pages 73 - 78


Questions

Questions
?
Project 1
Project 1 is available to work on now! You will be enhancing the
Cinema Entry console application. All the details can be found in
the Project 1 folder in eConestoga.
End of Lecture
End of Lecture 2

You might also like