Top Banner
Chapter 5: Programming with C# 1 Microsoft® Visual C# 2008
37

Chapter 5: Programming with C#

Feb 21, 2016

Download

Documents

Joana Soares

Microsoft® . Visual C# 2008. Chapter 5: Programming with C#. Overview. Using Arrays Using Collections Using Exception Handling Using Interfaces (optional) Using Delegates and Events (optional). Lesson: Using Arrays. What Is an Array? How to Create an Array - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter  5:   Programming with C#

Chapter 5: Programming with C#

1

Microsoft®

Visual C# 2008

Page 2: Chapter  5:   Programming with C#

Overview

Using ArraysUsing CollectionsUsing Exception Handling Using Interfaces (optional)Using Delegates and Events (optional)

2

Page 3: Chapter  5:   Programming with C#

Lesson: Using Arrays

3

What Is an Array?

How to Create an Array

How to Initialize and Access Array Members

How to Iterate Through an Array Using the foreach

Statement

How to Use Arrays as Method Parameters

How to Index an Object

Page 4: Chapter  5:   Programming with C#

What Is an Array?

A data structure that contains a number of variables called elements of

the array

All of the array elements must be of the same type

Arrays are zero indexed

Arrays are objects

Arrays can be:

o Single-dimensional, an array with the rank of one

o Multidimensional, an array with a rank greater than one

o Jagged, an array whose elements are arrays

Array methods

Page 5: Chapter  5:   Programming with C#

How to Create an Array

Declare the array by adding a set of square brackets to end of the variable

type of the individual elements

Instantiate to create

o int[ ] numbers = new int[5];

To create an array of type Object

o object [ ] animals = new object [100];

Int[] MyIntegerArray;

type[] array-name;

Syntax

Example

Page 6: Chapter  5:   Programming with C#

How to Initialize and Access Array Members

string[] animal = {"Mouse", "Cat", "Lion"};

animal[1]= "Elephant";

string someAnimal = animal[2];

int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

numbers[4] = 5;

Initializing an array

Accessing array members

Page 7: Chapter  5:   Programming with C#

How to Iterate Through an Array Using the foreach Statement

int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};

foreach (int i in numbers) {

Console.WriteLine(i);

}

Using foreach statement repeats the embedded statement(s) for each

element in the array

foreach ( type identifier in expression ) statement-block

Syntax

Examples

Page 8: Chapter  5:   Programming with C#

How to Use Arrays as Method Parameters

8

Pass an array to a method

Use the params keyword to pass a variable number of arguments to a

method

public int Sum(params int[] list) {int total = 0;foreach ( int i in list ) {

total += i;}return total;

}...// pe is the object providing Sum()...int value = pe.Sum( 1, 3, 5, 7, 9, 11 );

Page 9: Chapter  5:   Programming with C#

How to Index an Object

9

Use this keyword, and get and set accessors

public class Zoo {private Animal[] theAnimals;public Animal this[int i] {

get {return theAnimals[i];

}set {

theAnimals[i] = value;}

}}

Page 10: Chapter  5:   Programming with C#

10

Practice: Using a foreach Statement with an Array

In this practice, you will create an array, populate it, and use the foreach statement to print out the values in the array

Hands-on Practice

Page 11: Chapter  5:   Programming with C#

11

Practice (optional): Using an Indexer

In this practice, you will write an indexer for the Zoo class

Hands-on Practice

Page 12: Chapter  5:   Programming with C#

Lesson: Using Collections

12

What Are Lists, Queues, Stacks, and Hash Tables?

How to Use the ArrayList Class

How to Use Queues and Stacks

How to Use Hash Tables

Page 13: Chapter  5:   Programming with C#

What Are Lists, Queues, Stacks, and Hash Tables?

13

Lists, queues, stacks, and hash tables are common ways to manage data

in an application

List: A collection that allows you access by index

Example: An array is a list; an ArrayList is a list

Queue: First-in, first-out collection of objects

Example: Waiting in line at a ticket office

Stack: Last-in-first-out collection of objects

Example: A pile of plates

Hash table: Represents a collection of associated keys and

values

organized around the hash code of the key

Example: A dictionary

Page 14: Chapter  5:   Programming with C#

How to Use the ArrayList Class

14

ArrayList does not have a fixed size; it grows as needed

Use Add(object) to add an object to the end of the ArrayList

Use [] to access elements in the ArrayList

Use TrimToSize() to reduce the size to fit the number of elements in the ArrayList

Use Clear to remove all the elements

Can set the capacity explicitly

Page 15: Chapter  5:   Programming with C#

How to Use Queues and Stacks

15

Queues: first-in, first-out

o Enqueue places objects in the queue

o Dequeue removes objects from the queue

Stacks: last-in, first-out

o Push places objects on the stack

o Pop removes objects from the stack

o Count gets the number of objects contained in a stack or queue

Page 16: Chapter  5:   Programming with C#

How to Use Hash Tables

16

Book techBook = new Book("Inside C#", 0735612889);

// ...

public Hashtable bookList;

//

bookList.Add(0735612889, techBook);

//

Book b = (Book) bookList[0735612889];

// b’s title is "Inside C#”

A hash table is a data structure that associates a key with an object, for rapid retrieval

Key Object

Page 17: Chapter  5:   Programming with C#

17

Practice: Creating and Using Collections

In this practice, you will use the ArrayList class

Hands-on Practice

Page 18: Chapter  5:   Programming with C#

Lesson: Using Exception Handling

18

How to Use Exception Handling

How to Throw Exceptions

Page 19: Chapter  5:   Programming with C#

How to Use Exception Handling

19

Exception handling syntax

try {

// suspect code

}

catch {

// handle exceptions

}

finally {

// always do this

}

Page 20: Chapter  5:   Programming with C#

How to Throw Exceptions

20

Throw keyword

Exception handling strategies

Exception types

The predefined common language runtime exception classes

Example: ArithmeticException, FileNotFoundException

User-defined exceptions

Page 21: Chapter  5:   Programming with C#

21

Practice: Using Exception Handling

In this practice, you will use throw and catch an exception

Hands-on Practice

Page 22: Chapter  5:   Programming with C#

Lesson: Using Interfaces (optional)

22

What Is an Interface?

How to Use an Interface

How to Work with Objects That Implement Interfaces

How to Inherit Multiple Interfaces

Interfaces and the .NET Framework

Page 23: Chapter  5:   Programming with C#

What Is an Interface?

23

Is a reference type that defines a contract

Specifies the members that must be supplied by classes or

interfaces that implement the interface

Can contain methods, properties, indexers, events

Does not provide implementations for the members

Can inherit from zero or more interfaces

An interface:

Page 24: Chapter  5:   Programming with C#

How to Use an Interface

24

interface ICarnivore {

bool IsHungry { get; }

Animal Hunt();

void Eat(Animal victim);

}

An interface defines the same functionality and behavior to unrelated

classes

Declare an interface

Implement an interface

Page 25: Chapter  5:   Programming with C#

How to Work with Objects That Implement Interfaces

25

if ( anAnimal is ICarnivore ) {ICarnivore meatEater = (ICarnivore) anAnimal;Animal prey = meatEater.Hunt();meatEater.Eat( prey );

}

is

ICarnivore meatEater = anAnimal as ICarnivore;if ( meatEater != null ) {

Animal prey = meatEater.Hunt();meatEater.Eat( prey );

}

as

// is and as with an objectif ( prey is Antelope ) { ... }

Page 26: Chapter  5:   Programming with C#

How to Inherit Multiple Interfaces

26

Interfaces should describe a type of behavior

Examples:

o Lion is-a-kind-of Animal; Lion has Carnivore behavior

o Shark is-a-kind-of Animal; has Carnivore behavior

o Derive Lion and Shark from abstract class Animal

o Implement Carnivore behavior in an Interface

Class Chimpanzee : Animal, ICarnivore, IHerbivore { … }

Page 27: Chapter  5:   Programming with C#

Interfaces and the .NET Framework

27

Allows you to make your objects behave like .NET Framework objects

Example: Interfaces used by Collection classes

o ICollection, IComparer, IDictionary, IDictionary Enumerator,

o IEnumerable, IEnumerator, IHashCodeProvider, IList

public class Zoo : IEnumerable {

. . .

public IEnumerator GetEnumerator() {

return (IEnumerator)new ZooEnumerator(

this );

}

Page 28: Chapter  5:   Programming with C#

28

Practice: Using Interfaces

In this practice, you will implement the ICloneable interface

Hands-on Practice

Page 29: Chapter  5:   Programming with C#

Lesson: Using Delegates and Events

29

How to Create a Delegate

What Is an Event?

How to Write an Event Handler

Page 30: Chapter  5:   Programming with C#

How to Create a Delegate

30

Medical CenterScheduleApointment

CallsProcessNextPatient

DelegateAppointmentType

Zoo Keeper 1Schedule lion CheckClaws

Zoo Keeper 1Schedule lion CheckClaws

AntelopeCheckHooves

LionCheckClaws

Page 31: Chapter  5:   Programming with C#

What Is an Event?

31

Mouse and keyboard

MouseDown,MouseUp,MouseMove,MouseEnter,MouseLeave,MouseHover

KeyPress, KeyDown, KeyUp

Property

FontChangedSizeChangedCursorChanged

Page 32: Chapter  5:   Programming with C#

How to Write an Event Handler

32

Declare events using delegateso System.EventHandler is declared as a delegate

button1.Click += new System.EventHandler(button1_Click);

Event handler is called when the event occurso EventArgs parameter contains the event data

private void button1_Click(object sender, System.EventArgs e) {MessageBox.Show( e.ToString() );

}

Page 33: Chapter  5:   Programming with C#

33

Practice: Declaring and Calling a Delegate

In this practice, you will create and use a delegate

Hands-on Practice

Page 34: Chapter  5:   Programming with C#

Review

34

Using Arrays

Using Collections

Using Exception Handling

Using Interfaces

Using Delegates and Events

Page 35: Chapter  5:   Programming with C#

35

Lab 5:1: Using Arrays

Exercise 1: Sorting Numbers in an Array

Page 36: Chapter  5:   Programming with C#

36

Lab 5.2 (optional): Using Indexers and Interfaces

Exercise 1: Writing the Check Pick-up Application Exercise 2: Using Interfaces

Page 37: Chapter  5:   Programming with C#

37

Lab 5.3 (optional): Using Delegates and Events

Exercise 1: Working with Events and Delegates