Chapter 5: Programming with C#

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Data Structures and Collections
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Introduction to C# Properties, Arrays, Loops, Lists Game Design Experience Professor Jim Whitehead January 28, 2008 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
Object Composition Interfaces Collections Covariance Object class Programming using C# LECTURE 10.
Interfaces 1. Interfaces are (parts of) contracts Interfaces are contracts between implementers and consumers Consumers: Programmers using a class implementing.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
ILM Proprietary and Confidential -
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Understanding Data Types and Collections Lesson 2.
Arrays and Collections Tonga Institute of Higher Education.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Introduction to Object-Oriented Programming Lesson 2.
1 9/22/05CS360 Windows Programming Arrays, Collections, Hash Tables, Strings.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
 2002 Prentice Hall. All rights reserved. 1 Outline Mouse Event Handling Keyboard Event Handling Graphical User Interface Concepts:
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
Understanding Data Types and Collections Lesson 2.
Programming Right from the Start with Visual Basic .NET 1/e
Lecture 10 Collections Richard Gesick.
Sort & Search Algorithms
Chapter 9 Programming Based on Events
Advanced .NET Programming I 2nd Lecture
INF230 Basics in C# Programming
Computing with C# and the .NET Framework
Validating User Input Lesson 5.
Multidimensional Arrays
Chapter Eleven Handling Events.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
C# Programming Arrays in C# Declaring Arrays of Different Types Initializing Array Accessing Array Elements Creating User Interfaces Using Windows Standards.
Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
CS313D: Advanced Programming Language
Arrays, For loop While loop Do while loop
6 Delegate and Lambda Expressions
Conditional Statements
Exception Handling Chapter 9 Edited by JJ.
Object Oriented Programming in java
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
MSIS 655 Advanced Business Applications Programming
CIS 199 Final Review.
Fundaments of Game Design
Using a Queue Chapter 8 introduces the queue data type.
5. 3 Coding with Denotations
Using a Queue Chapter 8 introduces the queue data type.
Introduction to Programming
Interface 11: Interface Programming C# © 2003 DevelopMentor, Inc.
Defining Interfaces using C#
Review for Midterm 3.
Advanced .NET Programming I 3rd Lecture
Arrays.
Presentation transcript:

Chapter 5: Programming with C# Microsoft® Chapter 5: Programming with C# Visual C# 2008

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

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

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 Syntax type[] array-name; Example Int[] MyIntegerArray; Instantiate to create int[ ] numbers = new int[5]; To create an array of type Object object [ ] animals = new object [100];

How to Initialize and Access Array Members Initializing an array int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; numbers[4] = 5; Accessing array members string[] animal = {"Mouse", "Cat", "Lion"}; animal[1]= "Elephant"; string someAnimal = animal[2];

How to Iterate Through an Array Using the foreach Statement Using foreach statement repeats the embedded statement(s) for each element in the array Syntax foreach ( type identifier in expression ) statement-block Examples int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0}; foreach (int i in numbers) { Console.WriteLine(i); }

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

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;

Practice: Using a foreach Statement with an Array Hands-on Practice In this practice, you will create an array, populate it, and use the foreach statement to print out the values in the array

Practice (optional): Using an Indexer Hands-on Practice In this practice, you will write an indexer for the Zoo class

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

What Are Lists, Queues, Stacks, and Hash Tables? 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

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

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

How to Use Hash Tables A hash table is a data structure that associates a key with an object, for rapid retrieval 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#” Key Object

Practice: Creating and Using Collections Hands-on Practice In this practice, you will use the ArrayList class

Lesson: Using Exception Handling How to Use Exception Handling How to Throw Exceptions

How to Use Exception Handling Exception handling syntax try { // suspect code } catch { // handle exceptions finally { // always do this

How to Throw Exceptions Throw keyword Exception handling strategies Exception types The predefined common language runtime exception classes Example: ArithmeticException, FileNotFoundException User-defined exceptions

Practice: Using Exception Handling Hands-on Practice In this practice, you will use throw and catch an exception

Lesson: Using Interfaces (optional) 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

What Is 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

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

How to Work with Objects That Implement Interfaces is if ( anAnimal is ICarnivore ) { ICarnivore meatEater = (ICarnivore) anAnimal; Animal prey = meatEater.Hunt(); meatEater.Eat( prey ); } as ICarnivore meatEater = anAnimal as ICarnivore; if ( meatEater != null ) { Animal prey = meatEater.Hunt(); meatEater.Eat( prey ); } // is and as with an object if ( prey is Antelope ) { ... }

How to Inherit Multiple Interfaces Class Chimpanzee : Animal, ICarnivore, IHerbivore { … } 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

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

Practice: Using Interfaces Hands-on Practice In this practice, you will implement the ICloneable interface

Lesson: Using Delegates and Events How to Create a Delegate What Is an Event? How to Write an Event Handler

How to Create a Delegate Zoo Keeper 1 Schedule lion CheckClaws Zoo Keeper 1 Schedule lion CheckClaws Medical Center ScheduleApointment Calls ProcessNextPatient Delegate AppointmentType Lion CheckClaws Antelope CheckHooves

What Is an Event? Mouse and keyboard Property MouseDown, MouseUp, MouseMove, MouseEnter, MouseLeave, MouseHover KeyPress, KeyDown, KeyUp Property FontChanged SizeChanged CursorChanged

How to Write an Event Handler Declare events using delegates System.EventHandler is declared as a delegate button1.Click += new System.EventHandler(button1_Click); 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() ); }

Practice: Declaring and Calling a Delegate Hands-on Practice In this practice, you will create and use a delegate

Review Using Arrays Using Collections Using Exception Handling Using Interfaces Using Delegates and Events

Lab 5:1: Using Arrays Exercise 1: Sorting Numbers in an Array

Lab 5.2 (optional): Using Indexers and Interfaces Exercise 1: Writing the Check Pick-up Application Exercise 2: Using Interfaces

Lab 5.3 (optional): Using Delegates and Events Exercise 1: Working with Events and Delegates