building applications using c# and .net framework · 2014-01-29 · length specifies size of the...

40
BUILDING APPLICATIONS USING C# AND .NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6) Professional Program: Data Administration and Management Instructor: Michael Kremer, Ph.D. Technology & Information Management Class 4

Upload: others

Post on 22-Apr-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

BUILDING APPLICATIONS USING C# AND .NET

FRAMEWORK

(OBJECT-ORIENTED PROGRAMMING, X428.6)

Professional Program: Data Administration and Management

Instructor: Michael Kremer, Ph.D. Technology & Information Management

Class 4

Page 2: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

AGENDA

11. C# Arrays

12. C# Collections

13. Classes and Methods

Page 3: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

C# Arrays

11.

Page 4: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.1 INTRODUCTION TO C# ARRAYS

Value-type variable hold single value, objects (instantiated from

classes) hold complex data.

Between these two extremes: Arrays and Collections

Hold multiple instances of data, but in simpler way than classes.

Array is object to hold set of similar data.

Arrays can have many dimensions.

Imagine six different numbers,

need to calculate average:

Using an array processing of data is more efficient:

126

Page 5: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.2 ONE-DIMENSIONAL ARRAYS

Syntax to create an array:

Declaring creates variable

on the stack.

Initializing creates object

on the heap.

Declare and Initialize in

one step:

Length specifies size of the array, how many elements it

contains. Length of 5 means 5 elements (0,1,2,3,4).

Assign values to array: Array name

followed by index in square brackets:

127

Stack Heap

int[] numbers;

Numbers = new int[4];

numbers

numbers 0 1 2 3

Page 6: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.2 ONE-DIMENSIONAL ARRAYS

Declare, create, and assign

value in one statement:

Fixed-size array: Use a literal value to dimension the array

Many times you do not know the dimension at run-time.

Create variable length array: Instead of using a literal to size the

array use a variable instead:

128

Page 7: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

System.Array class provides many properties and methods.

Selected

Properties

Selected

Static

Methods

Syntax of calling static methods:

129

Property Description

IsFixedSize Return a Boolean indicating if an array has a fixed size or not.

IsReadOnly Returns a Boolean indicating if an array is read-only or not.

Length Returns the total number of items in all the dimensions of an array.

Rank Returns the number of dimensions of an array.

Static Method Description

BinarySearch(array, value) This method searches a one-dimensional sorted Array for a value, using a binary

search algorithm.

Clear(array, index, length) This method removes all items of an array and sets a range of items in the array

to 0.

Copy(array1,array2,length) This method copies a section of one Array to another Array and performs type

casting and boxing as required.

Reverse(array) This method reverses the order of the items in a one-dimensional Array or in a

portion of the Array.

Sort(array) This method sorts the items in one-dimensional Array objects.

Page 8: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

It is good practice to check the Rank property when using the

Length property. If Rank = 1, the Length represents number of

elements in array,

Selected Instance Methods:

Syntax to use Instance methods:

130

Instance Method Description

Clone() This method creates a shallow (=another reference pointing to the same object)

copy of the Array.

CopyTo(array, index) This method copies all the elements of the current one-dimensional Array to the

specified one-dimensional Array starting at the specified destination Array index.

GetLength(dimension) This method returns the number of items in a specific dimension of an Array.

GetLowerBound(dimension) This method returns the lower bound of an Array in a specific dimension.

GetUpperBound(dimension) This method returns the upper bound of an Array in a specific dimension.

Page 9: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

Two useful String methods when working with arrays:

Up to now, we have been able to declare arrays storing only one type of data. This strongly-typed nature of C# is in most cases desired.

Use keyword var to declare implicitly-typed array.

An Array can also hold objects of the same type!

131

String Method Description

Join(array, joinCharacter) Concatenates all the elements of a string array, using the specified

joinCharacter between each element.

Split(splitCharacters) Returns an array of strings where each element is a substring that is delimited

by the specified character or characters.

Page 10: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

132

Page 11: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

133

Page 12: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.3 ARRAY PROPERTIES AND METHODS

134

Page 13: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

11.4 MULTI-DIMENSIONAL ARRAYS

Two or more dimensions. Two-dimensional arrays are also

referred to as rectangular arrays (store rows and columns of

data).

Use commas inside square brackets to separate dimensions:

To assign or read values from a rectangular array use a nested

loop:

135

Page 14: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

C# Collections

12.

Page 15: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.1 OVERVIEW OF C# COLLECTIONS

.NET Base Class Library contains a wide array of collection classses.

Two main categories of collection classes:

Associative collection classes (key/value pair to store data)

Non-accociative collection classes (simply a value is stored)

Generics collection introducted in .NET 2.0 (System.Collections.Generics)

Associative collections store a value in the collection by providing a key that is used to add/remove/lookup the item.

Most useful when you need to lookup/manipulate a collection using a key value.

Non-associative collections do not use keys to manipulate the collection but rely on the object itself being stored or some other means (such as index) to manipulate the collection.

136

Page 16: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.1 OVERVIEW OF C# COLLECTIONS

Collections used to be untyped (before .NET 2.0), that means

they could hold any type of object within one collection. This lead

to run-time errors when processing data of varying type.

Since .NET 2.0 collections are typed, meaning they have to be

declared as a type,

such as int, for

example, that is the

collection could

only hold integer

values.

Why not use arrays?

With arrays, you must declare a size at some point.

Inserting or removing elements in the middle is very inefficient

137

.NET 2.0 and after .NET 1.X Description

List<type> ArrayList Uses an index to access each element. Very efficient for

accessing elements sequentially.

SortedList<key type,

value type>

SortedList Acts like a lookup table, having a key and value pair to

store data. This list is automatically sorted by the key value.

Queue<type> Queue Uses methods to add/remove elements (FIFO)

Stack<type> Stack Uses method to add/remove elements (LIFO)

Page 17: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.1 OVERVIEW OF C# COLLECTIONS

System.Collections.Generics

138

Collection Ordering Contiguous

Storage

Direct

Access

Notes

Dictionary Unordered Yes Via Key Best for high performance lookups.

SortedDictionary Sorted No Via Key Compromise of Dictionary speed and ordering, uses binary

search tree.

SortedList Sorted Yes Via Key Very similar to SortedDictionary, except tree is

implemented in an array, so has faster lookup on

preloaded data, but slower loads.

List User has precise

control over element

ordering

Yes

Via Index Best for smaller lists where direct access required and no

sorting.

LinkedList User has precise

control over element

ordering

No

No

Best for lists where inserting/deleting in middle is

common and no direct access required.

HashSet Unordered Yes Via Key Unique unordered collection, like a Dictionary except key

and value are same object.

SortedSet Sorted No Via Key Unique sorted collection, like SortedDictionary except key

and value are same object.

Stack LIFO Yes Only Top Essentially same as List<T> except only process as LIFO

Queue FIFO Yes Only

Front

Essentially same as List<T> except only process as FIFO

Page 18: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.2 DICTIONARY OBJECT

Dictionary objects are most commonly used collection object

when it comes to storing a key value type pair of data.

Very similar to a database lookup table, one column is key or ID,

and the other one is the description column.

Syntax:

To add data use the Add method, or directly assign data:

Common

properties

and

methods

139

Indexer Description

[index] Gets or sets the value associated with the specified key.

Property Description

Count Gets the number of elements in the dictionary object.

Keys Gets a collection containing the keys in the dictionary object.

Values Gets a collection containing the values in the dictionary object.

Method Description

Add(TKey,TValue) Adds the specified key and value to the dictionary.

Clear() Removes all elements from the list and sets its Count property to zero.

ContainsKey(TKey) Returns a Boolean that indicates if the dictionary object contains the specified key.

Remove(Tkey) Removes the value with the specified key from the dictionary object.

Page 19: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.2 DICTIONARY OBJECT

140

Page 20: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.2 DICTIONARY OBJECT

141

Page 21: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.3 LIST OBJECT

A list object is very similar to an array, it just stores one type (as

opposed to Key/Value pair) using an index.

But it overcomes the shortfalls of an array as stated earlier, for

example, you do not dimension a list object, its space

requirement is limited by memory resources only.

Syntax:

You can optionally

set the initial

capacity of the list

object in the

parentheses.

If you omit the

capacity, it is set

to 16.

142

Indexer Description

[index] Gets or sets the elements at the specified index (zero-based).

Property Description

Capacity Gets or sets the number of elements the list can hold.

Count Gets the number of elements in the list.

Method Description

Add(object) Adds an element to the end of a list and returns the element’s index.

Clear() Removes all elements from the list and sets its Count property to zero.

Contains(object) Returns a Boolean that indicates if the list contains the specified object.

Insert(index,object) Inserts an element into the list at the specified index.

Remove(object) Removes the first occurrence of the specified object from the list.

RemoveAt(index) Removes the element at the specified index of a list.

BinarySearch(object) Searches a list for a specified object and returns the index for that object.

Sort() Sorts the elements in a list into ascending order.

Page 22: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.3 LIST OBJECT

143

Page 23: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.3 LIST OBJECT

144

Page 24: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.4 QUEUE AND STACK OBJECTS

Queues and Stacks objects are special objects in that they do

not have an indexer to set or get items.

No add method, instead, the Queue object has Enqueue and

Dequeue methods to add and retrieve items and the Stack

object has the Push and Pop methods.

Queue object processes

items on a First In,

First Out (FIFO) basis

145

Queue Object

5 4 3 2 1

End Start

Property Description

Count Gets the number of items in the queue

Method Description

Enqueue(object) Adds the specified object to the end of the queue.

Dequeue() Gets the object at the start and removes it from the queue.

Clear() Removes all items from the queue.

Peek() Retrieves the next item in the queue without deleting it.

Page 25: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.4 QUEUE AND STACK OBJECTS

Stack object operates on the opposite principle compared to the

Queue object.

Its items are processed based on

Last In, First Out (LIFO) concept.

146

Stack Object

5

4

3

2

1 Bottom

Top

Property Description

Count Gets the number of items in the queue

Method Description

Push(object) Adds the specified object to the end of the stack.

Pop() Gets the object at the top and removes it from the stack.

Clear() Removes all items from the stack.

Peek() Retrieves the next item in the stack without deleting it.

Page 26: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.4 QUEUE AND STACK OBJECTS

147

Page 27: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.4 QUEUE AND STACK OBJECTS

148

Page 28: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

12.4 QUEUE AND STACK OBJECTS

149

Page 29: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

Classes and Methods

13.

Page 30: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.1 CLASSES

Class Architecture

Classes are simply contained in files:

There can be more than one class in one file.

One class may be spread among separate physical files, each class then

needs the attribute partial.

Used only class files that are associated with the Windows form.

Create individual class files that hold code that you want to

share in your application.

Database application structure code in a different layers/tiers:

Presentation

Business

Database

150

Page 31: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.1 CLASSES

Main advantage of separating the

three different functionalities is for

maintenance purposes.

Also supports the concept of code

abstraction.

Code abstraction means to break up

spaghetti code into smaller

manageable pieces and to move

repeating logic into one central place.

Also individual classes can be used

in other applications. (DB layer!).

Classes can be placed on different

servers for performance reasons.

151

Presentation Layer

Windows

Form

Classes

Classes

supporting

User Interface

(UI)

Business Access Layer

Business

Classes

Data Access Layer

Database

Classes

DB Server

Database

App Server

User Computer

Page 32: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.1 CLASSES

152

Page 33: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.1 CLASSES

Object-Oriented Programming in Classes

Model the real world: Real world is made up of objects that

relate to each other.

Static classes: No need to instantiate, use for overall

functionality rather than specific instance functionality.

Syntax for classes:

Internal: Can be used within the same assembly (default)

Public: Can be used within the entire solution.

153

Page 34: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

Methods are the lowest structures to hold your code.

Methods are like procedures and functions in other

programming languages, they perform some kind of evaluation

and may or may not return a value to the calling program.

Syntax:

Public: Available in your entire program (depends on whether class is

Internal or Public)

Private: Only available in the class

Static: Method that is available at the class level and not at the object

(Instance) level.

154

Page 35: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

Void: Method

does not return

a value.

When returning a

value, you must use

the return keyword

in the method to

return a value of the

return type specified.

155

Page 36: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

156

Page 37: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

Methods Arguments/Parameters

Methods may have parameters, meaning values or references

that are passed into the method.

Parameter list is comprised of the type of the parameter

followed by the name of the parameter.

When using multiple parameters, you simply comma-separate

the parameters.

Call a method from in the same class: Use method name followed by

possible arguments.

Call a method in a different class: Use namespace, a dot operator,

followed by the method name.

157

Page 38: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

first two arguments are

references to values in

textbox controls, the third

one is simply a literal value

(hard-coded).

These arguments are

passed by ordinal position

into the method.

The method then uses these values and then returns a value

back to the calling environment.

New in .NET 4.0: Optional arguments, named arguments

When setting default value for a parameter, the parameter

becomes optional:

158

Page 39: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

Instead of using the positional notation of assigning arguments

to parameters, you can also use the named notation.

Additional

parameter

modifiers

159

Parameter

Modifier

Description

(None) If a parameter is not marked with a parameter modifier, it is assumed to be passed by

value, meaning the called method receives a copy of the original data.

Out Output parameters must be assigned by the method being called, and therefore are

passed by reference. If the called method fails to assign output parameters, you are

issued a compiler error.

Ref The value is initially assigned by the caller and may be optionally reassigned by the

called method (as the data is also passed by reference). No compiler error is

generated if the called method fails to assign a ref parameter.

params This parameter modifier allows you to send in a variable number of arguments as a

single logical parameter. A method can have only a single params modifier, and it

must be the final parameter of the method. In reality, you may not need to use the

params modifier all too often, however be aware that numerous methods within the

base class libraries do make use of this C# language feature.

Page 40: Building Applications using C# and .net framework · 2014-01-29 · Length specifies size of the array, how many elements it contains. Length of 5 means 5 elements ... Fixed-size

13.2 METHODS

Overloading Methods

Overloading: Methods having the same name but different

number or type of parameters.

Design choice:

Overloading

Optional arguments

160