37
Module 5: Programming with C#

Module 5 : Programming with C#

Embed Size (px)

DESCRIPTION

Module 5 : Programming with C#. Overview. Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events. Lesson: Using Arrays. What Is an Array? How to Create an Array How to Initialize and Access Array Members - PowerPoint PPT Presentation

Citation preview

Page 1: Module  5 : Programming with C#

Module 5:Programming with C#

Page 2: Module  5 : Programming with C#

Overview

Using Arrays

Using Collections

Using Interfaces

Using Exception Handling

Using Delegates and Events

Page 3: Module  5 : Programming with C#

Lesson: Using Arrays

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: Module  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:

Single-dimensional, an array with the rank of one Multidimensional, an array with a rank greater than one Jagged, an array whose elements are arrays

Array methods

Page 5: Module  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

int[ ] numbers = new int[5];

To create an array of type Object

object [ ] animals = new object [100];

int[] MyIntegerArray; int[] MyIntegerArray;

Page 6: Module  5 : Programming with C#

How to Initialize and Access Array Members

Initializing an array

Accessing array members

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

numbers[4] = 5;

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

numbers[4] = 5;

string[] animal = {"Mouse", "Cat", "Lion"}; animal[1]= "Elephant";string someAnimal = animal[2];

string[] animal = {"Mouse", "Cat", "Lion"}; animal[1]= "Elephant";string someAnimal = animal[2];

Page 7: Module  5 : Programming with C#

How to Iterate Through an Array Using the foreach Statement

Using foreach statement repeats the embedded statement(s) for each element in the array

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

foreach (int i in numbers) {

Console.WriteLine(i);

}

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

foreach (int i in numbers) {

Console.WriteLine(i);

}

Page 8: Module  5 : Programming with C#

How to Use Arrays as Method Parameters

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 );

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: Module  5 : Programming with C#

How to Index an Object

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;}

}}

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

get {return theAnimals[i];

}set {

theAnimals[i] = value;}

}}

Page 10: Module  5 : Programming with C#

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

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 PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 11: Module  5 : Programming with C#

Practice (optional): Using an Indexer

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

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

Hands-on PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 12: Module  5 : Programming with C#

Lesson: Using Collections

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: Module  5 : Programming with C#

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

List: A collection that allows you access by indexExample: An array is a list; an ArrayList is a list

Queue: First-in, first-out collection of objectsExample: Waiting in line at a ticket office

Stack: Last-in-first-out collection of objectsExample: A pile of plates

Hash table: Represents a collection of associated keys and values organized around the hash code of the keyExample: A dictionary

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

Page 14: Module  5 : Programming with C#

How to Use the ArrayList Class

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: Module  5 : Programming with C#

How to Use Queues and Stacks

Queues: first-in, first-out

Enqueue places objects in the queue

Dequeue removes objects from the queue

Stacks: last-in, first-out

Push places objects on the stack

Pop removes objects from the stack

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

Page 16: Module  5 : Programming with C#

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

How to Use Hash Tables

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#"

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#"

ObjectObjectKeyKey

Page 17: Module  5 : Programming with C#

Practice: Creating and Using Collections

In this practice, you will use the ArrayList class

In this practice, you will use the ArrayList class

Hands-on PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 18: Module  5 : Programming with C#

Lesson: Using Interfaces

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 19: Module  5 : Programming with C#

What Is an Interface?

An interface:

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

Page 20: Module  5 : Programming with C#

How to Use an Interface

An interface defines the same functionality and behavior to unrelated classes

Declare an interface

Implement an interface

interface ICarnivore {bool IsHungry { get; }Animal Hunt();void Eat(Animal victim);

}

interface ICarnivore {bool IsHungry { get; }Animal Hunt();void Eat(Animal victim);

}

Page 21: Module  5 : Programming with C#

How to Work with Objects That Implement Interfaces

is

as

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

}

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

}

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

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

}

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

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

}

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

Page 22: Module  5 : Programming with C#

How to Inherit Multiple Interfaces

Interfaces should describe a type of behavior

Examples:

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

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

Derive Lion and Shark from abstract class Animal

Implement Carnivore behavior in an Interface

class Chimpanzee: Animal, ICarnivore, IHerbivore { … }class Chimpanzee: Animal, ICarnivore, IHerbivore { … }

Page 23: Module  5 : Programming with C#

Interfaces and the .NET Framework

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

Example: Interfaces used by Collection classes

ICollection, IComparer, IDictionary, IDictionary Enumerator, IEnumerable, IEnumerator, IHashCodeProvider, IList

public class Zoo : IEnumerable {. . .public IEnumerator GetEnumerator() {

return (IEnumerator)new ZooEnumerator( this );}

public class Zoo : IEnumerable {. . .public IEnumerator GetEnumerator() {

return (IEnumerator)new ZooEnumerator( this );}

Page 24: Module  5 : Programming with C#

Practice: Using Interfaces

In this practice, you will implement the ICloneable interface

In this practice, you will implement the ICloneable interface

Hands-on PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 25: Module  5 : Programming with C#

Lesson: Using Exception Handling

How to Use Exception Handling

How to Throw Exceptions

Page 26: Module  5 : Programming with C#

How to Use Exception Handling

Exception handling syntax

try {// suspect code

}catch {

// handle exceptions}finally {

// always do this}

try {// suspect code

}catch {

// handle exceptions}finally {

// always do this}

Page 27: Module  5 : Programming with C#

How to Throw Exceptions

Throw keyword

Exception handling strategies

Exception types

The predefined common language runtime exception classes

Example: ArithmeticException, FileNotFoundException

User-defined exceptions

Page 28: Module  5 : Programming with C#

Practice: Using Exception Handling

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

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

Hands-on PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 29: Module  5 : Programming with C#

Lesson: Using Delegates and Events

How to Create a Delegate

What Is an Event?

How to Write an Event Handler

Page 30: Module  5 : Programming with C#

How to Create a Delegate

Medical CenterScheduleApointment

Medical CenterScheduleApointment

CallsProcessNextPatient

DelegateAppointmentType

CallsProcessNextPatient

DelegateAppointmentType

Zoo Keeper 2Schedule antelope

CheckHooves

Zoo Keeper 2Schedule antelope

CheckHooves

Zoo Keeper 1Schedule lion CheckClaws

Zoo Keeper 1Schedule lion CheckClaws

AntelopeCheckHooves

AntelopeCheckHooves

LionCheckClaws

LionCheckClaws

Page 31: Module  5 : Programming with C#

What Is an Event?

Mouse and keyboard

Property

MouseDown,MouseUp,MouseMove,MouseEnter,MouseLeave,MouseHover

MouseDown,MouseUp,MouseMove,MouseEnter,MouseLeave,MouseHover

KeyPress, KeyDown, KeyUp

KeyPress, KeyDown, KeyUp

FontChangedSizeChangedCursorChanged

FontChangedSizeChangedCursorChanged

Page 32: Module  5 : Programming with C#

How to Write an Event Handler

Declare events using delegates

System.EventHandler is declared as a delegate

Event handler is called when the event occurs

EventArgs parameter contains the event data

private void button1_Click(object sender, System.EventArgs e) {

MessageBox.Show( e.ToString() );

}

private void button1_Click(object sender, System.EventArgs e) {

MessageBox.Show( e.ToString() );

}

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

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

Page 33: Module  5 : Programming with C#

Practice: Declaring and Calling a Delegate

In this practice, you will create and use a delegate

In this practice, you will create and use a delegate

Hands-on PracticeHands-on PracticeHands-on PracticeHands-on Practice

10 min

Page 34: Module  5 : Programming with C#

Review

Using Arrays

Using Collections

Using Interfaces

Using Exception Handling

Using Delegates and Events

Page 35: Module  5 : Programming with C#

Lab 5.1: Using Arrays

Exercise 1: Sorting Numbers in an Array

30 minutes

Page 36: Module  5 : Programming with C#

Lab 5.2 (optional): Using Indexers and Interfaces

Exercise 1: Writing the Check Pick-up Application

Exercise 2: Using Interfaces

1 hour

Page 37: Module  5 : Programming with C#

Lab 5.3 (optional): Using Delegates and Events

Exercise 1: Working with Events and Delegates

1 hour