More Related Content
Similar to Csharp Hands On Lab Paul Yao
Similar to Csharp Hands On Lab Paul Yao (18)
Csharp Hands On Lab Paul Yao
- 1. C# Hands On Lab Embedded Windows Developers Conference
Microsoft Windows Embedded Developers Conference
HANDS-ON LAB
Introduction to C#
Developed by
Paul Yao
The Paul Yao Company
http://www.paulyao.com
© Copyright 2001-2002 The Paul Yao Company Page 1 of 28
http://www.paulyao.com
- 2. C# Hands On Lab Embedded Windows Developers Conference
HANDS-ON LAB
Introduction to C#
Copyright © 2001-2002 The Paul Yao Company. All Rights Reserved.
This document may be reproduced provided that the document is reproduced in its entirety, and
provided that the original copyright notice is included.
Windows is a registered trademark of Microsoft Corporation
© Copyright 2001-2002 The Paul Yao Company Page 2 of 28
http://www.paulyao.com
- 3. C# Hands On Lab Embedded Windows Developers Conference
Introduction
This hands-on lab introduces programmers to key features of the C#
language, the Common Language Runtime (CLR), and the Visual
Studio .NET development environment.
Objectives.
In this Hands-On session, you work with Visual Studio .NET to build C# applications.
You can build applications for either the desktop, using the .NET Framework, or for
Windows CE-based platforms, using the .NET Compact Framework.
The six exercises in this lab period introduce you to using Visual Studio. NET to build
character-based applications. The emphasis is on features unique to C#, to .NET, from
the perspective of a C or C++ programmer. Programmers familiar with Visual Basic
.NET will find many familiar concepts, and will get from these exercises an appreciation
for differences between the syntax of Visual Basic .NET and the syntax of C#.
After completing this set of exercises, you will be able to:
• Use Visual Studio.NET to create C# applications.
• Build, run, and debug C# programs using Visual Studio.NET.
• Work with basic data types, convert data types, and perform string operations.
• Define and use the elements of C# classes
• Use container classes and enumerate through containers
• Write code to intercept and handle exceptions; raise exceptions.
Lab Configuration
Each workstation has the following software installed.
• Windows XP Professional
• Visual Studio.NET "Everett"
• .NET Framework Libraries
For More Information on C#
http://msdn.microsoft.com/vstudio/techinfo/articles/upgrade/Csharpintro.asp
Estimated Time to Complete These Labs
60 Minutes
Index of Exercises
Exercise 1 – Creating Character-Based Console I/O...........................................................4
Exercise 2 – Common C# Value Types...............................................................................8
Exercise 3 – Defining Classes............................................................................................12
Exercise 4 – Containers.....................................................................................................18
Exercise 5 – Enumerating Objects.....................................................................................22
Exercise 6 – Exception Handling.......................................................................................25
© Copyright 2001-2002 The Paul Yao Company Page 3 of 28
http://www.paulyao.com
- 4. C# Hands On Lab Embedded Windows Developers Conference
Exercise 1 – Creating Character-Based Console I/O
This exercise shows you how to create the classic Hello World program using the C#
programming language and the Microsoft Visual Studio.NET development environment.
Objectives
After completing this exercise, you will be able to:
Create a new project in Visual Studio.NET. (step 1-2)
Write a character-based program to display a character string. (step 3-5)
Identify the entry point to a C# program. (step 6)
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
Objective 1: Create a new project in Visual Studio.NET
1. Start Visual Studio.NET a. Click the following menu item: Start -> Programs ->
Microsoft Visual Studio.NET -> Microsoft Visual
Studio.NET
2. Create a new Empty a. Within the Visual Studio.NET IDE, select this menu:
project File->New->Project…
b. In the Project Types list, select "Visual C# Projects"
(See below for .NET c. In the templates list, select "Empty Project"
Compact Framework) d. In the project Name, type a project name with your
name (first or last) followed by the number '1' (for
exercise 1) as in "PaulYao1".
e. Click Ok.
.NET Compact Framework Changes
To build for the .NET Compact Framework, follow steps 'a' and 'b' as
listed above. Then, continue with step 'c', below:
c. In the template list, select "Smart Device Application".
d. Name your project with your name + '1" (example: PaulYao1).
e. Click Ok.
f. In the "Smart Device Application Wizard", do not pick Pocket PC
since it does not support console applications. Instead::
• For platform, pick "Windows CE"
• For project type, pick "Empty Project"
© Copyright 2001-2002 The Paul Yao Company Page 4 of 28
http://www.paulyao.com
- 5. C# Hands On Lab Embedded Windows Developers Conference
Objective 2: Write a character-based program to display a character
string
3. Add a new code file to a. Select the File -> Add New Item… menu
the project b. In the Templates window, click on the "Code File"
icon.
c. Click Open.
4. Write a program that a. Add the code listed below to your source file.
displays the character string
"Hello Character World" on
the command line.
using System;
class Hello
{
static void Main()
{
System.Console.WriteLine("Hello Character World");
System.Console.ReadLine();
}
}
Things To Note:
The using keyword identifies the assemblies that we expect to use in our program.
Visual Studio.NET uses the metadata found in each assembly to learn about the
available namespaces, classes, and methods. The metadata also describes the
© Copyright 2001-2002 The Paul Yao Company Page 5 of 28
http://www.paulyao.com
- 6. C# Hands On Lab Embedded Windows Developers Conference
number of parameters, the type of parameters, and the return type for each
method.
C# code is organized using namespaces and classes. This code calls a method
named WriteLine, a method in a class named Console. The Console class resides
in the System namespace. A period (".") separates a namespace name from a
class, and a class name from a method name.
5. Build and run your a. Build your program using the menu command Build ->
program Build Solution. As an option, you can also use the
shortcut key, namely Ctrl+Shift+B.
b. Run your program using the menu command Debug-
>Start Without Debugging. As an alternative, you
could hit the Ctrl+F5 shortcut keystroke.
c. You see a window open, like the fragment shown here:
Hello Character World
Press any key to continue
.NET Compact Framework Changes
To run in the Windows CE emulator:
• Make sure the "Device" selection toolbar is visible – Right-Click
on the menu, then make sure there is a checkmark next to the
"Device" item.
• In the device toolbar, make sure that "Windows CE .NET
Emulator" is highlighted, as shown here:
• Start running as indicated above – by selecting Debug -> Start
Without Debugging, or by hitting <Ctrl>+F5.
Objective 3: Identify the entry point to a C# program
6. Use the debugger to find a. If the program is running, stop it.
the program entry point. b. Step into the debugger, using either a menu selection or
a keystroke:
• Menu: Debug -> Step Into
• Key: <F11>
c. Experiment with using the following keys to learn
about the built-in debugger:
© Copyright 2001-2002 The Paul Yao Company Page 6 of 28
http://www.paulyao.com
- 7. C# Hands On Lab Embedded Windows Developers Conference
• <F9> - Set breakpoint at current cursor position
• <F10> - Step Over (single-step, stay in current
function)
• <F11> - Step Into (single-step, follow calls into
functions)
• <F5> - Continue (resume normal execution)
Things To Note:
The entry point for a C# program is the method Main.
Main must be a static method (note the keyword "static" in the code).
In C#, methods must appear inside classes – the is no such thing as a global
function as in C or C++. That is why Main is in the Hello class.
More Things To Try
If you have extra time, here are some things to try. For each numbered item, build and
run your program:
1. What happens if you remove the using System; statement? What if, in addition, you
remove the System reference in the call to System.Console.WriteLine? Hint: don't
forget to remove the period that follows System., so that the resulting call is
Console.WriteLine("Hello Character World");
2. Move the Main method out of the Hello class? (That is, delete the keywords class
Hello and the associated curly braces.)
3. What happens if you clone class Hello - copy it, paste it, and rename it to something
like Hello2?
© Copyright 2001-2002 The Paul Yao Company Page 7 of 28
http://www.paulyao.com
- 8. C# Hands On Lab Embedded Windows Developers Conference
Exercise 2 – Common C# Value Types
This exercise introduces you to basic C# data types, shows how to convert between data
types, and introduces basic string operators.
Objectives
After completing this exercise, you will be able to:
Write code to allocate fundamental C# Value types, including byte, int, and long.
Write code to use the allocated Value types
Write code to convert different Value types to a string for display to the user.
Perform various string operations.
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
1. Create a new Windows a. Within the Visual Studio.NET IDE, select this menu:
Application project File->New->Project…
b. In the Project Types list, select "Visual C# Projects"
c. In the templates list, select "Console Application"
Note: select "Smart Device Application" for .NET
Compact Framework; then for the platform select
"Windows CE".
d. In the project Name, type a project name with your
name (first or last) followed by the number '2' (for
exercise 2) as in "PaulYao2".
e. Click Ok.
2. Allocate a variable of a. Within the Main method, allocate a local variable of
type byte, determine the type byte named b. At the start of Main, type the
maximum value that can be following line of code:
stored, convert that value to byte b;
a string, and display it.
b. Set the initial value of this byte to the maximum value
that can be stored in a byte. Do this by accessing the
static byte.MaxValue() method, as in:
b = byte.MaxValue;
c. Convert this to a string by calling the static method
byte.ToString(). Display the results in the console
window:
Console.WriteLine("Maximum Byte is " +
b.ToString());
3. Allocate a 32-bit variable a. Within the Main method, allocate a local variable of
of type int, determine the type int named i. At the start of Main, type the
© Copyright 2001-2002 The Paul Yao Company Page 8 of 28
http://www.paulyao.com
- 9. C# Hands On Lab Embedded Windows Developers Conference
maximum value that can be following line of code:
stored, and display it. int i;
b. Set the initial value of this 32-bit integer to the
maximum value that can be stored in an integer. Do
this by accessing the static int.MaxValue() method, as
in:
b = int.MaxValue;
c. Convert this to a string by calling the static method
int.ToString(). Display the results:
Console.WriteLine("Maximum int is " +
i.ToString());
4. Allocate a 64-bit variable a. Within the Main method, allocate a local variable of
of type long, determine the type long named l. At the start of Main, type the
maximum value that can be following line of code:
stored, and display it. long l;
b. Set the initial value of this 64-bit integer to the
maximum value that can be stored in a long value. Do
this by accessing the static method long.MaxValue(),
as in:
l = long.MaxValue;
c. Convert this to a string by calling the static method
long.ToString(). Display the results:
Console.WriteLine("Maximum long is " +
l.ToString());
5. Allocate two strings, then a. Allocate two strings using the type string, as shown
concatenate them – using here:
the “+” operator – to form a string strFirst = "Hello ";
string strSecond = "World";
third string. Display the
resulting string.
b. Allocate a third string, and initialize it with the
previous two strings appended together – as in:
String strThird = strFirst + strSecond;
c. Display the resulting string using the following code:
Console.WriteLine(strThird);
6. Determine the length of a a. Calculate the size length of a string, strThird, using
string using the public code like the following:
property String.Length. int cchLength = strThird.Length;
Call the String.Substring
method to cut some b. Allocate a string holding the length, and display it
characters from the middle using code like this:
string strFourth = "Length is " +
© Copyright 2001-2002 The Paul Yao Company Page 9 of 28
http://www.paulyao.com
- 10. C# Hands On Lab Embedded Windows Developers Conference
of a string. Display the cchLength.ToString();
Console.WriteLine(strFourth);
results of both operations.
c. Call the String.Substring to cut a string out from
another string. Display the string:
Console.WriteLine(strThird.Substring(0,5))
;
7. Allocate a DateTime a. To allocate a DateTime object, you must call the new
object, initialize its contents operator, as in this code:
to today's date, and display DateTime dt = new DateTime(2002, 10, 24);
the string.
b. Like other types, the DateTime class has a ToString
method to convert the object to a string, using code like
this:
string strFifth = dt.ToString();
c. Display this string using code like this:
Console.WriteLine(strFifth);
Things To Note:
C# provides two basic categories of types: Value types and Reference types.
Value types directly hold their data, while reference types hold a reference - a
pointer - to the value on the heap. In the code you wrote, all of the integer types
are Value types. DateTime is also a Value type. The String class, on the other
hand, is a Reference type.
You created several different types of integers, each with a different maximum
value. You saw that C# provides 8-bit, 32-bit, and 64 bit integers. Each of these
types is fully supported in the .NET Common Language Runtime (CLR). There is
one more integer size that you did not create - a 16-bit integer, which is available
using the short keyword. The C# types byte, short, int, and long are aliases for
the following CLR Value types: System.Byte, System.Int16, System.Int32, and
System.Int64.
There is a rich set of string operators that make it easy to create, concatenate, and
perform operations on strings. If you do a lot of string operations, you should look
into the StringBuilder class instead of the String class. The String class creates a
new memory object for each operation, while StringBuilder performs most of its
operations on a single string – thus making it more efficient from the perspective
of memory usage.
The DateTime class stores dates and times. A related structure, TimeSpan, can
be used to store the results of subtracting one date from another.
More Things To Try
If you have extra time, here are some things to try. For each numbered item, build and
run your program:
1. In addition to its integer types, C# also supports float (32-bit floating point), double
(64-bit floating point), as well as decimal (128-bit floating point) which guarantees
© Copyright 2001-2002 The Paul Yao Company Page 10 of 28
http://www.paulyao.com
- 11. C# Hands On Lab Embedded Windows Developers Conference
precision when performing operations on monetary values. Write some code using all
of these types, and display the results in the console window. (Each type provide a
ToString method.)
2. Search the help database for other members of the String class, and experiment with
them. Display your results in the console window.
3. Experiment with the StringBuilder class to create strings, concatenate strings, and
display strings in the console window.
4. Experiment with creating a TimeSpan by subtracting one DateTime from another.
Display the results in the console window.
© Copyright 2001-2002 The Paul Yao Company Page 11 of 28
http://www.paulyao.com
- 12. C# Hands On Lab Embedded Windows Developers Conference
Exercise 3 – Defining Classes
This exercise introduces you to some of the unique features of C# classes.
Objectives
After completing this exercise, you will be able to:
Describe the difference between static & instance methods (steps 1-4).
Inherit from an existing class to create a new class (steps 5-6)
Add properties to a class, including read-only properties, write-only properties,
and read/write properties (steps 7-8)
Implement a dynamic link library which contains a class (steps 9-14).
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
Objective 1: Describe the difference between static and instance
methods.
1. Create a new Windows a. Within the Visual Studio.NET IDE, select this menu:
Application project File->New->Project…
b. In the Project Types list, select "Visual C# Projects"
c. In the templates list, select "Console Application"
Note: select "Smart Device Application" for .NET
Compact Framework; then for the platform select
"Windows CE".
d. In the project Name, type a project name with your
name (first or last) followed by the number '3' (for
exercise 3) as in "PaulYao3".
e. Click Ok.
2. Create a class named 'A' a. Browse the source file window that is open. Look for
that contains an instance the "namespace" keyword, which appears in blue, and
method and a static method. the curley-brace "{" that follows that keyword.
b. In the line following the two lines mentioned above,
define a new class by typing code like the following:
class A
{
static public void Static_Member()
{
Console.WriteLine("Calling from Static_Member");
}
public void Instance_Member()
{
Console.WriteLine("Calling from Instance_Member");
}
}
© Copyright 2001-2002 The Paul Yao Company Page 12 of 28
http://www.paulyao.com
- 13. C# Hands On Lab Embedded Windows Developers Conference
Things To Note:
A static functions starts with the keyword 'static'.
The 'public' keyword says that methods are accessible from outside the class.
3. Within the body of the a. Locate the Main function.
Main function, call each of b. Add code like the following:
these functions.
A myA = new A();
A.Static_Member(); // Call static methods with class name.
myA.Instance_Member(); // Use instance to call instance method.
Things To Note:
Call static functions by specifying the name of the class followed by the name of
the function.
Call instance functions by specifying an instance of the object, followed by the
name of the function.
4. Build and run your a. You should see output like the following:
program.
Objective 2: Inherit from an existing class to create a new class
5. Create a class named 'B' a. Add code like the following:
that inherits from class 'A'.
Create three private integer
values in the class.
class B : A
{
private int m_x;
private int m_y;
private int m_z;
}
Things To Note:
Just like in C++, the colon operator indicates inheritance from a base class.
C# classes can hold data members and member functions, just as in C++.
6. Create an instance of B. a. Within the Main function, type code like the
Call its member functions, following:
and attempt to access its
© Copyright 2001-2002 The Paul Yao Company Page 13 of 28
http://www.paulyao.com
- 14. C# Hands On Lab Embedded Windows Developers Conference
private data members.
B myB = new B();
B.Static_Member();
myB.Instance_Member();
m_x = 1;
m_y = 2;
m_z = 3;
Things To Note:
You will be able to call the member functions, but the private data members are
not accessible. For that you need to define properties. A property looks like a data
member, but it has a public "get" and/or "set" member that allows the reading or
writing of a value that is controlled by a function call.
Objective 3: Add properties to a class, including read-only properties,
write-only properties, and read/write properties
7. Modify class B to add a a. Within the Main function, type code like the following:
read-only property (X), a
write-only property (Y), and
a read/write property (Z).
public int X
{
get { return m_x; }
}
public int Y
{
set { m_y = value; }
}
public int Z
{
get { return m_z; }
set { m_z = value; }
}
8. Write code to read from a. Type the following code in the Main function.
& write to each of these b. Build your program.
properties. c. When you get errors – and you will – jump to each
error message in turn by hitting these keys: <Alt> +
<F12>.
d. Comment out the lines that cause errors until you can
build without errors. Run your program.
myB.X = 1;
myB.Y = 1;
© Copyright 2001-2002 The Paul Yao Company Page 14 of 28
http://www.paulyao.com
- 15. C# Hands On Lab Embedded Windows Developers Conference
myB.Z = 1;
Console.WriteLine(myB.X.ToString());
Console.WriteLine(myB.Y.ToString());
Console.WriteLine(myB.Z.ToString());
Things To Note:
Uninitialized data members have a default value of zero.
Objective 4: Implement a dynamic link library which contains a class.
9. Create a new dynamic a. Create a second project in Visual Studio .NET. Do this
link library. by following these steps:
• Open the Solution Explorer window (menu View ->
Solution Explorer)
• Right-Click the top-line – the one that says
"Solution" on it – and from the popup menu picking
the command Add -> New Project . . .
• You see the "Add New Project" window.
b. The item you select depends on whether you are
building for the desktop or for Smart Devices:
• For the desktop, select "Class Library"
• For a .NET Compact Framework library, select
"Smart Device Application" template, then pick
"Class Library in the Smart Device application
wizard.
c. For the project name, use your name followed by the
letters "ALib" as in "PaulYaoALib".
d. Click Ok.
10. Move class 'A' from a. Delete (Cut) the source file from the application
your application to the DLL source file and copy it (Paste) to the DLL source file.
source file.
11. Build library & a. Select menu Build -> Build Solution.
application b. Fix whatever build errors you encounter. The next step
fixes a build error by creating a reference to the library
in the application project.
12. Fix missing assembly a. If you deleted class A, you see this error message:
reference.
"The type or namespace name 'A' could not be
found (are you missing a using directive or an
assembly reference?)"
b. Open the Solution Explorer window – select the
following menu item: View -> Solution Explorer. In
the Solutions Explorer window:
© Copyright 2001-2002 The Paul Yao Company Page 15 of 28
http://www.paulyao.com
- 16. C# Hands On Lab Embedded Windows Developers Conference
• Find the application tree (example: 'PaulYao3')
• Find the "References" folder in the application tree
and Right-click on this folder
• Select Add Reference. . . in the popup menu. This
opens the Add Reference window.
c. In the Add Reference window:
• Click the [Projects] tab.
• Double-click on the library project.
• Click Ok.
14. Make sure that class is a. In the Solution Explorer window:
public and add a 'using' • Right-Click the library you added in the previous
directive step.
• Select the View In Object Browser menu item.
b. You see output like the following in the object browser
window:
The library "paulyaoalib" contains namespace
"paulyaoalib" which contains two public classes, A
and Class1.
c. If you do not see class A, modify your library by
appending the keyword "public" to the class A
declaration, like this:
public class A
Rebuild your library. Note that the Object Browser
caches its information. To see changes, you need to
add the library to the Object Browser window a second
time.
d. In the application, add a reference to the library
namespace with the 'using' directive:
using PaulYaoALib;
© Copyright 2001-2002 The Paul Yao Company Page 16 of 28
http://www.paulyao.com
- 17. C# Hands On Lab Embedded Windows Developers Conference
Things To Note:
You can use the object browser to explore all of the system libraries, and it will
provide lots of interesting details. For example, the object browser shows that the
base class for the class we created, class A, is System.Object. This is the
case, even though we did not explicitly name this as our base class.
© Copyright 2001-2002 The Paul Yao Company Page 17 of 28
http://www.paulyao.com
- 18. C# Hands On Lab Embedded Windows Developers Conference
Exercise 4 – Containers
This exercise introduces you to three types of containers: fixed-length arrays, variable-
length arrays, and queues. These are three of the many kinds of container classes – also
known as "collection classes" – available to .NET programmers.
Objectives
After completing this exercise, you will be able to:
Write code to allocate, initialize, and access data in fixed-length arrays
(steps 1 – 4).
Write code to allocate, initialize, and access data in variable-length arrays
(step 5).
Write code to allocate, initialize, and access data in a queue (step 6).
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
Objective 1 – Write code to allocate, initialize, and access data in
fixed-length arrays.
1. Create a new Windows a. Within the Visual Studio.NET IDE, select this menu:
Application project File->New->Project…
b. In the Project Types list, select "Visual C# Projects"
c. In the templates list, select "Console Application"
Note: select "Smart Device Application" for .NET
Compact Framework; then for the platform select
"Windows CE".
d. In the project Name, type a project name with your
name (first or last) followed by the number '4' (for
exercise 4) as in "PaulYao4".
e. Click Ok.
2. Create and initialize an a. Here is what the desired output looks like:
array of 5 integers. Dump
the contents of the array to
the console:
b. Enter code like that shown below.
c. Build and run your program
int[] i = new int[5] {10, 20, 30, 40, 50};
int j;
for (j = 0; j < 5; j++)
{
Console.WriteLine("Index= " + j.ToString() +
© Copyright 2001-2002 The Paul Yao Company Page 18 of 28
http://www.paulyao.com
- 19. C# Hands On Lab Embedded Windows Developers Conference
" & Value = " +
i[j].ToString());
}
3. Create and initialize an a. Here is what the desired output looks like:
array of 3 strings. Dump the
contents of the array to the
console. b. Enter code like that shown below.
c. Build and run your program
string[] str = new string[3] {"One", "Two", "Three" };
int iStr;
for (iStr = 0; iStr < 3; iStr++)
{
Console.WriteLine("Index= " + iStr.ToString() +
" & Value = " + str[iStr]);
}
4. Create and initialize an a. Here is what the desired output looks like:
array of 2 dates. Dump the
contents of the array to the
console. b. Enter code like that shown below.
c. Build and run your program
DateTime[] dt = new DateTime[2]
{
new DateTime(2002,5,1), new DateTime(2002, 6,1)
};
int iDate;
for (iDate = 0; iDate < 2; iDate++)
{
Console.WriteLine("Index= " + iDate.ToString() +
" & Date = " + dt[iDate].ToShortDateString());
}
Things To Note:
Array support built into C# creates fixed size arrays.
Arrays are allocated using the 'new' operator, just like other objects. Like other
objects, the memory management is the same – the garbage collector reclaims the
memory for objects that are unreachable.
You can create arrays for int, string, and date types, as shown here, and also for
other value types including float, decimal, etc. In addition, array elements can be
© Copyright 2001-2002 The Paul Yao Company Page 19 of 28
http://www.paulyao.com
- 20. C# Hands On Lab Embedded Windows Developers Conference
of any type, including an array type. When building .NET Windows Forms
applications, for example, the following two lines would be valid:
// Arrays can be created for any type, including
// for Windows Forms controls and fonts, as shown here:
Control [] acc = new System.Windows.Forms.Control[4];
System.Drawing.Font [] myFonts = new System.Drawing.Font[15];
Objective 2 – Write code to allocate, initialize, and access data in
variable-length arrays.
5. Create an ArrayList a. The desired output is shown here:
and add three elements of
different types – say a
string, an integer, and a
date. Display the contents of b. Enter code like that shown below.
the array on the console. c. Build and run your program
ArrayList al = new ArrayList();
al.Add("Hello");
al.Add(new DateTime(2002,10,23));
al.Add(15);
Console.WriteLine(al[0]);
Console.WriteLine(al[1]);
Console.WriteLine(al[2]);
Things To Note:
Fixed-length arrays must contain objects of the same type. An ArrayList array can
hold objects of different types.
Objective 3 – Write code to allocate, initialize, and access data in a
queue.
6. Create a Queue and add a. The desired output is shown here:
three elements of different
types. Display the elements
on the console.
b. Enter code like that shown below.
c. Build and run your program
Queue q = new Queue();
q.Enqueue("Compact Framework");
q.Enqueue(new Decimal(123.456) );
q.Enqueue(654.321);
© Copyright 2001-2002 The Paul Yao Company Page 20 of 28
http://www.paulyao.com
- 21. C# Hands On Lab Embedded Windows Developers Conference
Console.WriteLine(q.Dequeue());
Console.WriteLine(q.Dequeue());
Console.WriteLine(q.Dequeue());
Things To Note:
A .NET Queue can hold any type of object.
Add elements to a queue by calling Queue.Enqueue.
Remove elements from a queue by calling Queue.Dequeue.
© Copyright 2001-2002 The Paul Yao Company Page 21 of 28
http://www.paulyao.com
- 22. C# Hands On Lab Embedded Windows Developers Conference
Exercise 5 – Enumerating Objects
This exercise introduces you to the basics of enumerating objects in the .NET framework
using the C# foreach keyword.
Objectives
After completing this exercise, you will be able to:
Enumerate through a fixed-length array (steps 1-2)
Enumerate through an ArrayList collection (step 3)
Enumerate through a Queue collection (step 4)
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
Objective 1: Enumerate through a fixed-length array
1. Open the project from a. Within the Visual Studio.NET IDE, select this menu:
exercise 4 File->Open->Project…
b. Select the project name from the previous exercise. If
you had been following the established convention, you
have been using <your-name>4 – for example,
PaulYao4.
c. Click Ok.
2. Use the foreach statement a. Locate the three simple arrays created – one for string,
to enumerate through the array, and integer.
contents of a simple array. b. Modify the loop to use the foreach statement, as shown
in the following code:
// Integer array
int[] i = new int[5] {10, 20, 30, 40, 50};
foreach (int j in i)
{
Console.WriteLine("Value = " + j.ToString());
}
// String array
string[] str = new string[3] {"One", "Two", "Three" };
foreach (string s in str)
{
Console.WriteLine("Value = " + s);
}
// DateTime array
DateTime[] dt = new DateTime[2]
{
new DateTime(2002,5,1), new DateTime(2002, 6,1)
© Copyright 2001-2002 The Paul Yao Company Page 22 of 28
http://www.paulyao.com
- 23. C# Hands On Lab Embedded Windows Developers Conference
};
foreach (DateTime thisdate in dt)
{
Console.WriteLine("Value = " + thisdate.ToShortDateString());
}
Things To Note:
An index to count items is not required – the iteration walks though the exact
number of items in each array.
Objective 2: Enumerate through an ArrayList collection
3. Use the foreach a. Locate the ArrayList defined in the last exercise.
statement to access the b. Modify the code to use the foreach iterator to display
elements of an the contents of the array, using code like the following:
ArrayList.
ArrayList al = new ArrayList();
al.Add("Hello");
al.Add(new DateTime(2002,10,23));
al.Add(15);
foreach (object ob in al)
{
Console.WriteLine(ob);
}
Things To Note:
Since an ArrayList can hold different kinds of objects, you use the base type
object for the iteration.
You can enumerate any class with the C# foreach statement if the class
supports a GetEnumerator method. To enumerate programming languages
besides C# - say Visual Basic .NET – a class must implement the IEnumerable
interface.
Objective 3: Enumerate through a Queue collection.
4. Use the foreach a. Locate the Queue in the last exercise.
statement to access the b. Modify the code to use the foreach iterator to display
elements of a Queue. the contents of the queue, using code like the
following:
Queue q = new Queue();
q.Enqueue("Compact Framework");
q.Enqueue(new Decimal(123.456) );
q.Enqueue(654.321);
© Copyright 2001-2002 The Paul Yao Company Page 23 of 28
http://www.paulyao.com
- 24. C# Hands On Lab Embedded Windows Developers Conference
foreach (object o in q)
{
Console.WriteLine(o);
}
Things To Note:
Since a Queue can hold different kinds of objects, you use the base type object
for the iteration.
When you access the elements of a queue with an iterator, it does not change the
contents of the queue. The other technique for accessing queue elements – using
the Dequeue statement – does cause elements to be removed.
© Copyright 2001-2002 The Paul Yao Company Page 24 of 28
http://www.paulyao.com
- 25. C# Hands On Lab Embedded Windows Developers Conference
Exercise 6 – Exception Handling
This exercise introduces you to the syntax for C# exceptions.
Objectives
After completing this exercise, you will be able to:
Write code to catch exceptions. (steps 1-5)
Write termination handling code. (steps 6-7)
Write code that throws an exception. (step 8)
Steps
Instructions. The left column describes the purpose of a given step. The right column
provides detailed directions to accomplish the step.
Objective 1: Write code to catch exceptions.
1. Create a new Windows c. Within the Visual Studio.NET IDE, select this menu:
Application project File->New->Project…
d. In the Project Types list, select "Visual C# Projects"
e. In the templates list, select "Console Application"
Note: select "Smart Device Application" for .NET
Compact Framework; then for the platform select
"Windows CE".
f. In the project Name, type a project name with your
name (first or last) followed by the number '6' (for
exercise 6) as in "PaulYao6".
g. Click Ok.
2. Create the skeleton code a. Basic exception handling involves the key words try
for an exception and catch. The basic skeleton appears here:
try
{
}
catch (System.Exception except)
{
}
Things To Note:
C# exception syntax is the same as that for C++ exception handling.
The try block contains the mainline execution code.
The catch block contains the exception handling code.
3. Add code that displays a a. Add in four calls to Console.WriteLine, as in the
message before, during, and example below.
after the exception block. b. Build and run your program.
Test your code.
© Copyright 2001-2002 The Paul Yao Company Page 25 of 28
http://www.paulyao.com
- 26. C# Hands On Lab Embedded Windows Developers Conference
Console.WriteLine("1. Before");
try
{
Console.WriteLine("2. In try block");
}
catch (System.Exception e)
{
Console.WriteLine("3. In exception block");
}
Console.WriteLine("4. After");
The output looks like this:
Things To Note:
During normal program execution, the exception block does not execute.
4. Add code that generates a. The sample code, below, creates an array overflow
an exception. Examples exception.
worth trying include divide- b. Put the exception code OUTSIDE the exception block.
by zero, array overflow. c. Build and run your program – what happens to an
unhandled exception?
d. Move the exception code INSIDE the try block.
e. Build and run your program..
int[] i = new int[2];
i[2] = 5;
5. To determine the cause of a. Add the following code to the catch block of your
an exception, you can exception handling code.
examine members of the
System.Exception-
based objects. Add code to
do that in your program
Console.WriteLine("Type = " + e.GetType());
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("Source = " + e.Source);
Console.WriteLine("StackTrace = " + e.StackTrace );
Console.WriteLine("TargetSite = " + e.TargetSite);
Objective 2: Write termination handling code.
6. Create an empty try – a. Enter code like the following.
finally block. b. Build and run your program.
© Copyright 2001-2002 The Paul Yao Company Page 26 of 28
http://www.paulyao.com
- 27. C# Hands On Lab Embedded Windows Developers Conference
Console.WriteLine("A. Before");
try
{
Console.WriteLine("B. During");
}
finally
{
Console.WriteLine("C. In finally block");
}
Console.WriteLine("D. After finally block");
Things To Note:
The finally block is part of normal program execution.
The finally block executes whatever cleanup might be needed for the try
block – closing a network connection, closing a file, writing a record to a
database.
Termination handling (try-finally) can be integrated with an exception
(try-catch) block to guarantee cleanup even when an exception has occurred.
There is no C++ support for try/finally. However, Win32 does have support that is
provided with the __try and __finally keywords (note the leading pair of
underscores, "__", for each of these keywords).
7. Add a catch block to the a. Your code appears as below – new items are in bold.
existing try-finally block. b. Build and run the program.
Console.WriteLine("A. Before");
try
{
Console.WriteLine("B. During");
}
catch (System.Exception e)
{
Console.WriteLine("B.5. In exception block");
}
finally
{
Console.WriteLine("C. In finally block");
}
Console.WriteLine("D. After finally block");
© Copyright 2001-2002 The Paul Yao Company Page 27 of 28
http://www.paulyao.com
- 28. C# Hands On Lab Embedded Windows Developers Conference
Objective 3: Write code that throws an exception.
8. Throw an exception using a. Add code, like that shown below, to your program –
the C# throw statement. first OUTSIDE a try-block.
b. Build and run the program.
c. Move the code to inside a try-block.
d. Build and run your program again.
throw(new System.Exception("Whoops - hens do not have teeth"));
Things To Note:
To generate an exception, you create a new object – either of type
System.Exception, or of a type derived from System.Exception.
There are three constructors for System.Exception, allowing you to modify the
type of exception you create.
© Copyright 2001-2002 The Paul Yao Company Page 28 of 28
http://www.paulyao.com