Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Module 4:

Arrays, Statements and Exceptions

First Name Last Name 20pt


Job Title 20pt

Today’s Date 18pt

Avanade Confidential – Do Not Copy, Forward or Circulate 1


© Copyright 2011 Avanade Inc. All Rights Reserved.
Module Overview

• Creating and Using Arrays


• Introduction to Statements
• Using Selection Statements
• Using Iteration Statements
• Using Jump Statements
• Handling Basic Exceptions
• Raising Exceptions

Avanade Confidential – Do Not Copy, Forward or Circulate 2


© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 1:
Creating and Using Arrays

Avanade Confidential – Do Not Copy, Forward or Circulate 3


© Copyright 2011 Avanade Inc. All Rights Reserved.
Creating and Using Arrays

• What Is an Array?
• Creating and Initializing Arrays
• Common Properties and Methods Exposed by Arrays
• Accessing Data in an Array

Avanade Confidential – Do Not Copy, Forward or Circulate 4


© Copyright 2011 Avanade Inc. All Rights Reserved.
What Is an Array?

• An array is a sequence of elements that are grouped


together
Array features include:

Every element in the array contains a value

Arrays are zero-indexed

The length of an array is the total number of elements it can contain

The lower bound of an array is the index of its first element

Arrays can be single-dimensional, multidimensional, or jagged

The rank of an array is the number of dimensions in the array


Avanade Confidential – Do Not Copy, Forward or Circulate 5
© Copyright 2011 Avanade Inc. All Rights Reserved.
Creating and Initializing Arrays

• An array can have more than one dimension


Single [4.1.1 Creating Array]

Type[] arrayName = new Type[ Size ];

Multiple [4.1.2 Creating Array / 4.1.3 Creating Array]

Type[ , ] arrayName = new Type[ Size1, Size2];

Jagged [4.1.4 Creating Array / 4.1.5 Creating Array]]

Type [][] JaggedArray = new Type[size][];

Avanade Confidential – Do Not Copy, Forward or Circulate 6


© Copyright 2011 Avanade Inc. All Rights Reserved.
Common Properties and Methods Exposed by
Arrays

Length [4.1.6 Common Properties]

int[] oldNumbers = { 1, 2, 3, 4, 5 };
int numberCount = oldNumbers.Length;

Rank [4.1.7 Common Properties]

int[] oldNumbers = { 1, 2, 3, 4, 5 };
int rank = oldNumbers.Rank;

Avanade Confidential – Do Not Copy, Forward or Circulate 7


© Copyright 2011 Avanade Inc. All Rights Reserved.
Common Properties and Methods Exposed by
Arrays
[4.1.8 Common Methods]
CopyTo()

int[] oldNumbers = { 1, 2, 3, 4, 5 };
int[] newNumbers = new
int[oldNumbers.Length];
oldNumbers.CopyTo(newNumbers, 0);

Clone() [4.1.9 Common Methods]

int[] numbers = { 1, 2, 3, 4, 5 };
int[] numbersClone = (int[])numbers.Clone();

Sort() [4.1.10 Common Methods]

int[] oldNumbers = { 5, 2, 1, 3, 4 };
Array.Sort(oldNumbers);

Avanade Confidential – Do Not Copy, Forward or Circulate 8


© Copyright 2011 Avanade Inc. All Rights Reserved.
Accessing Data in an Array

• Elements are accessing from 0 to N-1


Accessing specific elements [4.1.11 Accessing Data]

int[] oldNumbers = { 1, 2, 3, 4, 5 };
int number = oldNumbers[2];
// OR
object number = oldNumbers.GetValue(2);

Iterating through all elements [4.1.12 Accessing Data / 4.1.13 Accessing Data]

int[] oldNumbers = { 1, 2, 3, 4, 5 };
...
for (int i = 0; i < oldNumbers.Length; i++)
{
int number= oldNumbers[i];
}
// OR
foreach (int number in oldNumbers) { ... }
Avanade Confidential – Do Not Copy, Forward or Circulate 9
© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 2:
Introduction to Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 10


© Copyright 2011 Avanade Inc. All Rights Reserved.
Introduction to Statements

• Statement Blocks
• Types of Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 11


© Copyright 2011 Avanade Inc. All Rights Reserved.
Statement Blocks
[4.2.1 Blocks / 4.2.2 Blocks]

• Use braces As • A block and its • Sibling blocks can


block delimiters parent block cannot have variables with
{ have a variable with the same name
// code the same name {

} { int i;
int i; ...
... }
{ ...
int i; {
... int i;
} ...
} }

Source: Add slide source information here, 9pt Arial (copy & paste onto other slides for correct position)

Avanade Confidential – Do Not Copy, Forward or Circulate 12


© Copyright 2011 Avanade Inc. All Rights Reserved.
Types of Statements

Selection Statements

• The if and switch statements

Iteration Statements

• The while, do, for and foreach statements

Jump Statements

• The goto, break and continue statements

Avanade Confidential – Do Not Copy, Forward or Circulate 13


© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 3:
Using Selection Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 14


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Decision Statements

• Using One-Way If Statements


• Using Either-Or If Statements
• Using Multiple-Outcome If Statements
• Using the Switch Statement
• Guidelines for Choosing a Decision Construct

Avanade Confidential – Do Not Copy, Forward or Circulate 15


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using One-Way If Statements
Syntax [4.3.1 One-Way If]

if ([condition]) [code to execute]

// OR

if ([condition])
{
[code to execute if condition is true]
}

Conditional operators:
OR represented by || AND represented by &&

Example [4.3.2 One-Way If]

if ((percent >= 0) && (percent <= 100))


{
// Add code to execute if a is greater than 50 here.
} Avanade Confidential – Do Not Copy, Forward or Circulate 16
© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Either-Or If Statements

• Provide an additional code block to execute if [condition]


evaluates to a Boolean false value
[4.3.3 Either-Or If / 4.3.4 Either-Or If / 4.3.5 Either-Or If]
Example

if (a > 50)
{
// Greater than 50 here
}
else
{
// less than or equal to 50 here
}

// OR

string carColor = "green";

string response = (carColor == "red") ?


"You have a red car" :
"You do not have a red car";
Avanade Confidential – Do Not Copy, Forward or Circulate 17
© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Multiple-Outcome If Statements

• You can combine several if statements to create a


multiple-outcome statement
Example [4.3.6 Multiple If]

if (a > 50)
{
// Add code to execute if a is greater than 50 here.
}
else if (a > 10)
{
// Add code to execute if a is greater than 10 and less than
// or equal to 50 here.
}
else
{
// Add code to execute if a is less than or equal to 50 here.
}

Avanade Confidential – Do Not Copy, Forward or Circulate 18


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using the Switch Statement

• The switch statement enables you to execute one of


several blocks of code depending on the value of a
variable or expression
Example [4.3.7 Switch / 4.3.8 Switch]

switch (a)
{
case 0:
// Executed if a is 0.
break;

case 1:
case 2:
case 3:
// Executed if a is 1, 2, or 3.
break;

default:
// Executed if a is any other value.
break;
} Avanade Confidential – Do Not Copy, Forward or Circulate 19
© Copyright 2011 Avanade Inc. All Rights Reserved.
Guidelines for Choosing a Decision Construct

Use an if structure when you have a single condition that controls the execution of
a single block of code

Use an if/else structure when you have a single condition that controls the
execution of one of two blocks of code

Use an if/elseif/else structure to run one of several blocks of code based on


conditions that involve several variables

Use a nested if structure to perform more complicated analysis of conditions that


involve several variables

Use a switch statement to perform an action based on the possible values of a


single variable

Avanade Confidential – Do Not Copy, Forward or Circulate 20


© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 4:
Using Iteration Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 21


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Iteration Statements

• The while Statement


• The do Statement
• The for Statement
• The foreach Statement
• Quiz: Spot the Bugs

Avanade Confidential – Do Not Copy, Forward or Circulate 22


© Copyright 2011 Avanade Inc. All Rights Reserved.
Types of Iteration Statements

• Iteration statements include:


while
A while loop enables you to execute a block of code zero or
more times

do
A do loop enables you to execute a block of code one or
more times

for
A for loop enables you to execute code repeatedly a set number
of times Avanade Confidential – Do Not Copy, Forward or Circulate 23
© Copyright 2011 Avanade Inc. All Rights Reserved.
Using the While Statement
The syntax of a while loop contains:

The while keyword to define the while loop

A condition that is tested at the start of each iteration

A block of code to execute for each iteration

Example [4.4.1 While]

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

Avanade Confidential – Do Not Copy, Forward or Circulate


0123456789 © Copyright 2011 Avanade Inc. All Rights Reserved.
24
Using the Do Statement
The syntax of a do loop contains:

The do keyword to define the do loop

A block of code to execute for each iteration

A condition that is tested at the end of each iteration

Example [4.4.2 Do]

int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 10);

Avanade Confidential – Do Not Copy, Forward or Circulate


0123456789 © Copyright 2011 Avanade Inc. All Rights Reserved.
25
Using the For Statement
The syntax of a for loop contains:

The for keyword to define the for loop

The loop specification (counter, starting value, limit, modifier)

A block of code to execute for each iteration

[4.4.3 For]
Example

for (int i = 0; i < 10; i++) {


Console.WriteLine(i);
}

0123456789

Avanade Confidential – Do Not Copy, Forward or Circulate 26


© Copyright 2011 Avanade Inc. All Rights Reserved.
The for Statement

• Place update information at the start of the loop [4.4.4 For]

for (int i = 0; i < 10; i++) {


Console.WriteLine(i);
}
0123456789

• Variables in a for block are scoped only within the block


for (int i = 0; i < 10; i++)
Console.WriteLine(i);
Console.WriteLine(i); // Error: i is no longer in scope

Avanade Confidential – Do Not Copy, Forward or Circulate 27


© Copyright 2011 Avanade Inc. All Rights Reserved.
The foreach Statement

• Choose the type and name of the iteration variable


• Execute embedded statements for each element of the
collection class
[4.4.5 Foreach]

ArrayList numbers = new ArrayList( );


for (int i = 0; i < 10; i++ ) {
numbers.Add(i);
}

foreach (int number in numbers) {


Console.WriteLine(number);
}

0123456789

Avanade Confidential – Do Not Copy, Forward or Circulate 28


© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 5:
Using Jump Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 29


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Jump Statements

• The goto Statement


• The break and continue Statements

Avanade Confidential – Do Not Copy, Forward or Circulate 30


© Copyright 2011 Avanade Inc. All Rights Reserved.
The goto Statement

• Flow of control transferred to a labeled statement


• Can easily result in obscure “spaghetti” code [4.5.1 Goto]

if (number % 2 == 0) goto Even;


Console.WriteLine("odd");
goto End;
Even:
Console.WriteLine("even");
End:;

Avanade Confidential – Do Not Copy, Forward or Circulate 31


© Copyright 2011 Avanade Inc. All Rights Reserved.
Break and Continue Statements
Break statement [4.5.2 Break]

while (oldNumbers.Length > count)


{
if (oldNumbers[count] == 5)
{
break; Enables you to exit the loop and skip
} to the next line of code
count++;
}

Continue statement [4.5.3 Continue]

while (oldNumbers.Length > count)


{
if (oldNumbers[count] == 5)
{ Enables you to skip the remaining
continue; code in the current iteration, test the
} condition, and then start the next
// Code that won't be hit iteration of the loop
count++;
}
Avanade Confidential – Do Not Copy, Forward or Circulate 32
© Copyright 2011 Avanade Inc. All Rights Reserved.
Lab 4.1: Using Statements

Time to complete: 30 minutes


• Exercise 1:
– Converting a Day of the Year
into a Month and Day Pair

Avanade Confidential – Do Not Copy, Forward or Circulate 33


© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 6:
Handling Basic Exceptions

Avanade Confidential – Do Not Copy, Forward or Circulate 34


© Copyright 2011 Avanade Inc. All Rights Reserved.
Handling Basic Exceptions

• Why Use Exceptions?


• Exception Objects
• Using try and catch Blocks
• Multiple catch Blocks

Avanade Confidential – Do Not Copy, Forward or Circulate 35


© Copyright 2011 Avanade Inc. All Rights Reserved.
What Is an Exception?

An exception is an indication of an error or exceptional condition, such as trying to


open a file that does not exist

When a method throws an exception, the calling code must be prepared to detect
and handle the exception

If the calling code cannot handle the exception, the exception is automatically
propagated to the code that invoked the calling code

The exception is propagated until a section of code handles the exception

If no code handles the exception, the runtime will report an unhandled exception
and the application will crash
Avanade Confidential – Do Not Copy, Forward or Circulate 36
© Copyright 2011 Avanade Inc. All Rights Reserved.
Why Use Exceptions?

• Traditional procedural error handling is cumbersome


Core program logic

int errorCode = 0;
FileInfo source = new FileInfo("code.cs");
if (errorCode == -1) goto Failed;
int length = (int)source.Length;
if (errorCode == -2) goto Failed;
char[] contents = new char[length];
if (errorCode == -3) goto Failed;
// Succeeded ...
Failed: ... Error handling

Avanade Confidential – Do Not Copy, Forward or Circulate 37


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using try and catch Blocks

• Object-oriented solution to error handling


– Put the normal code in a try block
– Handle the exceptions in a separate catch block [4.6.1 Try Catch]

try {
Console.WriteLine("Enter a number"); Program logic
int i = int.Parse(Console.ReadLine());
}
catch (OverflowException caught) Error handling

{
Console.WriteLine(caught);
}

Avanade Confidential – Do Not Copy, Forward or Circulate 38


© Copyright 2011 Avanade Inc. All Rights Reserved.
Multiple catch Blocks

• Each catch block catches one class of exception


• A try block can have one general catch block
• A try block is not allowed to catch a class that is derived
from a class caught in an earlier catch block [4.6.2 Try Catch]


try
{
Console.WriteLine("Enter first number");
int i = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number");
int j = int.Parse(Console.ReadLine());
int k = i / j;
}
catch (OverflowException caught) {…}
catch (DivideByZeroException caught) {…}
Avanade Confidential – Do Not Copy, Forward or Circulate 39
© Copyright 2011 Avanade Inc. All Rights Reserved.
Using Exception Properties
Common properties include: TargetSite

Message InnerException

Source HelpLink

StackTrace Data

[4.6.3 Try Catch]

try
{
// Try block.
}
catch (DivideByZeroException ex) Get the message
{ associated with the
Console.WriteLine(ex.Message); exception
}
Avanade Confidential – Do Not Copy, Forward or Circulate 40
© Copyright 2011 Avanade Inc. All Rights Reserved.
Lesson 7:
Raising Exceptions

Avanade Confidential – Do Not Copy, Forward or Circulate 41


© Copyright 2011 Avanade Inc. All Rights Reserved.
Raising Exceptions

• The throw Statement


• The finally Clause
• Checking for Arithmetic Overflow
• Guidelines for Handling Exceptions

Avanade Confidential – Do Not Copy, Forward or Circulate 42


© Copyright 2011 Avanade Inc. All Rights Reserved.
Exception Objects

Exception

SystemException

OutOfMemoryException

IOException

NullReferenceException

ApplicationException

Avanade Confidential – Do Not Copy, Forward or Circulate 43


© Copyright 2011 Avanade Inc. All Rights Reserved.
Creating an Exception Object
System.Exception

System.SystemException

System.FormatException

System.ArgumentException

System.NotSupportedException

+ many more

[4.7.1 Exception Object / 4.7.2 Exception Object / 4.7.3 Exception Object]

catch (Exception e)
{
FormatException ex =
new FormatException("Argument has the wrong format", e);
} Avanade Confidential – Do Not Copy, Forward or Circulate 44
© Copyright 2011 Avanade Inc. All Rights Reserved.
Throwing an Exception
throw keyword

throw [exception object];

Exception object declaration


Example [4.7.4 Throw]

public int GetIntegerRoot(int operand)


{
double root = Math.Sqrt(operand);
if (root != (int)root)
{
throw new ArgumentException("No integer root found.");
}
return (int)root;
}
Avanade Confidential – Do Not Copy, Forward or Circulate 45
© Copyright 2011 Avanade Inc. All Rights Reserved.
Using a Finally Block

Enables you to release resources and specify code that will always run,
whether an exception occurs or not
[4.7.5 Finally]

try
{
OpenFile("MyFile"); // Open a file
WriteToFile(...); // Write some data to the file
}
catch (IOException ex) Any catch blocks are
{ optional
MessageBox.Show(ex.Message);
}
finally
{
Logic that will always run
CloseFile("MyFile"); // Close the file
}

Avanade Confidential – Do Not Copy, Forward or Circulate 46


© Copyright 2011 Avanade Inc. All Rights Reserved.
Using the Checked and Unchecked Keywords

C# applications run with integer numeric overflow checking disabled by


default. You can change this project setting

You can control overflow checking for specific code by using the checked and
unchecked keywords

checked unchecked
{ {
int x = ...; int x = ...;
int y = ...; checked and int y = ...;
int z = ...; unchecked blocks int z = ...;
... ...
} }

... checked and ...


int z = checked(x* y); unchecked int z = unchecked(x* y);
... ... – Do Not Copy, Forward or Circulate
operators Avanade Confidential 47
© Copyright 2011 Avanade Inc. All Rights Reserved.
Checking for Arithmetic Overflow

• By default, arithmetic overflow is not checked


– A checked statement turns overflow checking on
[4.7.6 Arithmetic Overflow / 4.7.7 Arithmetic Overflow]

checked { OverflowException
int number = int.MaxValue;
Console.WriteLine(++number); Exception object is thrown.
} WriteLine is not executed.

unchecked {
int number = int.MaxValue; MaxValue + 1 is negative?
Console.WriteLine(++number);
}
-2147483648

Avanade Confidential – Do Not Copy, Forward or Circulate 48


© Copyright 2011 Avanade Inc. All Rights Reserved.
Guidelines for Handling Exceptions

"An error has occurred.


If the problem persists,
please contact an
administrator…"
"A connection to
database AvanadeDB
with password
'AVA12345' failed…"

Avanade Confidential – Do Not Copy, Forward or Circulate 49


© Copyright 2011 Avanade Inc. All Rights Reserved.
Guidelines for Handling Exceptions

• Throwing
– Avoid exceptions for normal or expected cases
– Never create and throw objects of class Exception
– Include a description string in an Exception object
– Throw objects of the most specific class possible

• Catching
– Arrange catch blocks from specific to general
– Do not let exceptions drop off Main

Avanade Confidential – Do Not Copy, Forward or Circulate 50


© Copyright 2011 Avanade Inc. All Rights Reserved.
Module Review and Takeaways

• Review Questions
• Best Practices

Avanade Confidential – Do Not Copy, Forward or Circulate 51


© Copyright 2011 Avanade Inc. All Rights Reserved.

You might also like