Professional Documents
Culture Documents
Avanade Capability - NET - CSharp - Module 4 - Arrays, Statements and Exceptions
Avanade Capability - NET - CSharp - Module 4 - Arrays, Statements and Exceptions
• What Is an Array?
• Creating and Initializing Arrays
• Common Properties and Methods Exposed by Arrays
• Accessing Data in an Array
int[] oldNumbers = { 1, 2, 3, 4, 5 };
int numberCount = oldNumbers.Length;
int[] oldNumbers = { 1, 2, 3, 4, 5 };
int rank = oldNumbers.Rank;
int[] oldNumbers = { 1, 2, 3, 4, 5 };
int[] newNumbers = new
int[oldNumbers.Length];
oldNumbers.CopyTo(newNumbers, 0);
int[] numbers = { 1, 2, 3, 4, 5 };
int[] numbersClone = (int[])numbers.Clone();
int[] oldNumbers = { 5, 2, 1, 3, 4 };
Array.Sort(oldNumbers);
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
• Statement Blocks
• Types of Statements
} { int i;
int i; ...
... }
{ ...
int i; {
... int i;
} ...
} }
Source: Add slide source information here, 9pt Arial (copy & paste onto other slides for correct position)
Selection Statements
Iteration Statements
Jump Statements
// OR
if ([condition])
{
[code to execute if condition is true]
}
Conditional operators:
OR represented by || AND represented by &&
if (a > 50)
{
// Greater than 50 here
}
else
{
// less than or equal to 50 here
}
// OR
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.
}
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
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:
int i = 0;
while (i < 10) {
Console.WriteLine(i);
i++;
}
int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 10);
[4.4.3 For]
Example
0123456789
0123456789
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
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?
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
try {
Console.WriteLine("Enter a number"); Program logic
int i = int.Parse(Console.ReadLine());
}
catch (OverflowException caught) Error handling
{
Console.WriteLine(caught);
}
•
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
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
Exception
SystemException
OutOfMemoryException
IOException
NullReferenceException
ApplicationException
System.SystemException
System.FormatException
System.ArgumentException
System.NotSupportedException
+ many more
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
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
}
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 { 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
• 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
• Review Questions
• Best Practices