how to code in c#

Post on 10-May-2015

1.002 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

How To Code in C# The Complete Course. From data types to object orientation. Includes code samples and exercises. Topics Getting Started with C# C# Language Fundamentals Branching Operators Object-Orientated Programming Classes and Objects Inside Methods Debugging Inheritance and Polymorphism Operator Overloading Structs Interfaces Arrays Collection Interfaces and Types Strings Throwing and Catching Exceptions Delegates and EventsGenerics New Language Features

TRANSCRIPT

1

Programming in  C#David Ringsell MCPD MCT MCAD

David Ringsell MCSD

Free .Net & SQL Server Web Tutorials

web and windows developmentprogramming in VB and C#

database developmentobject orientation

http://talk-it.biz/category/tutorials

3

Course ContentUnit Topic1. Getting Started with C#2. C# Language Fundamentals3. Branching4. Operators5. Object-Orientated Programming6. Classes and Objects7. Inside Methods8. Debugging9. Inheritance and Polymorphism

4

Course Content 2Unit Topic10. Operator Overloading11. Structs12. Interfaces13. Arrays14. Collection Interfaces and Types15. Strings16. Throwing and Catching Exceptions17. Delegates and Events18. Generics19. New Language Features

5

Your Consultant

David Ringsell MCPD MCPD MCT Trainer, developer, consultant Develops in C#.Net, VB.Net, ASP.Net and

Sequel Server More courses and tutorials: www.talk-it.biz david@talk-it.biz

6

References

Learning C# by J. Liberty from O’Reilly C# 2010 Professional from Wrox

7

1. Getting Started with C#

Why C# and not VB The C# Programming Language C# Goals How C# Fits with .Net Overview of the .NET Framework

8

Why C# and not VB

Syntax more like C++ and Java Syntax very concise Designed for object orientation

Started with a clean slateEverything is an object

Microsoft are evolving language

9

C# Supports ….

StructuredProcedural, blocked

Object-orientatedClasses, methods, properties

Event drivenEvent handlers, delegates

… programming

10

Safe Find bugs early in development process

Simple Few keywords

Internet Centric Designed for developing web programs

Hi Performance Designed for industrial strength programming

C# Goals

11

How C# Fits with .Net

Languages VB.Net, C#, C++ …

Visual Studio Integrated Development Environment (IDE) Framework Class Libraries (FCL)

ADO, ASP, XML, … Common Language Runtime (CLR) Windows Operating System

12

Overview of .Net

Win32

MessageQueuing

COM+(Transactions, Partitions,

Object Pooling)IIS WMI

Common Language Runtime

.NET Framework Class Library

ADO.NET: Data and XML

XML Web Services User Interface

VisualBasic C++ C#

ASP.NET

Perl J# …

13

2. C# Language Fundamentals

Data Types Numeric Types Non-Numeric Types: char and bool Variables Definite Assignment Constants Strings Statements

14

Data Types

Common C# intrinsic data types

Type Size in Bytes

byte 1

bool 2

int 4

long 8

float 4

double 8

decimal 12

15

Typing in C#

C# is a strongly typed language Types come in two flavours

Value (intrinsic)Reference (classes …)

Each type has a name (int) and size (4b) The .Net equivalents for int is Int32

16

Numeric Data Types

Unsigned (positive)byte, ushort, uint, ulong

Signed (positive or negative)short, int, long, float, decimal, double

Select the smallest type that will hold the required range of numbers

17

Non-Numeric Types: char and bool

charHolds just a single characterCan hold:

Simple character (‘A’) Unicode character (u\0041) Escape character (‘\n’)

boolHolds true or false in one byte

18

Declaring Local Variables

int myInt; System.Console.WriteLine("Uninitialized, myInt: {0}",myInt);

myInt = 5; int mySecondInt = 10; // declare and initialise int myInt4,myInt5; // declare multiple variables

What is the value on an integer before it is initialised?

19

Declaring Constants

const int FreezingPoint = 32; // degrees Farenheit

const int BoilingPoint = 212;

Why would you create constants?

20

Declaring Enumerations

// declare the enumeration

enum Temperatures:int

{

WickedCold = 0,

FreezingPoint = 32,

LightJacketWeather = 60,

SwimmingWeather = 72,

BoilingPoint = 212,

}

An enumeration is a set of named constants

Why would you create enumerations?

The data type defaults to int

21

Using Enumerations

System.Console.WriteLine("Freezing point of water: {0}", (int) Temperatures.FreezingPoint ); System.Console.WriteLine("Boiling point of water: {0}", (int) Temperatures.BoilingPoint );

22

Declaring Strings

string myString = “Hello World” ;// declare and initialise string

Where would you use strings

in your code?

A string is an object

23

Statements, Expressions & White Space A statement ends in a semicolon

int myInt = 23;

An expression can be part of an assignment myInt = myInt * 23;

White spaces are ignoredmyInt = myInt * 100;

24

Unit 2 Lab

To write statements that prompt and greet the user1. Open Visual Studio.Net and create a new C# Console Application project2. In the Main method insert the following line:

string myName;3. Write a statement that prompts users for their name.4. Write another statement that reads the user’s response from the keyboard and assigns it to the myName string.5. Add one more statement that prints “Hello myName” to the screen (where myName is the name the user typed in).6. Save your work.

25

Unit 2 Lab …When completed, the Main method should contain the following:

static void Main( ){

string myName;Console.WriteLine("Please enter your name");myName = Console.ReadLine( );Console.WriteLine("Hello {0}", myName);

}

26

3. Branching

A method is a mini program The statements in it executed from top to bottom Branching temporarily halts this execution to call

another method or statement There are 2 types of branching

Conditional Unconditional

27

Ways of Branching

Call a method Temporally transfer control to the called method

Looping Repeat statements (conditionally or unconditionally)

If Statements Execute statements only if condition true

Switch Statements Execute statements depending on value of variable

28

Calling MethodsStatement1

Statement2

MethodA()

Statement3

Statement4

End method

Statement1

Statement2

MethodB()

Statement3

Statement4

End method Statement1

Statement2

Statement3

Statement4

End method

Main

Method A

Method B

Call

Return

Call

Return

29

Branching to a Method

static void Main() { Console.WriteLine("In Main! Calling SomeMethod()..."); SomeMethod(); Console.WriteLine("Back in Main().");

} static void SomeMethod() { Console.WriteLine("Greetings from SomeMethod!"); }

30

If Statements

int valueOne = 10;int valueTwo = 20;

if ( valueOne > valueTwo ){ Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo);}

Condition (always in brackets)

Statement

31

Multiple Statement Block

if ( valueOne >= valueThree ) // true?{

Console.WriteLine( "valueOne: {0} larger or equal to valueThree: {1}", valueOne, valueThree);

Console.WriteLine("Good thing you tested again!");}

Braces create block

32

If … else Statements

if ( valueOne > valueTwo ) { Console.WriteLine( "ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo); } // end if else { Console.WriteLine( "Nope, ValueOne: {0} is NOT larger than valueTwo:

{1}",valueOne, valueTwo); } // end else

Execute if condition true

Execute if condition false

33

Nested if Statements

if (temp <= 32) { Console.WriteLine("Warning! Ice on road!"); if (temp == 32) Console.WriteLine( "Temp exactly freezing, beware of water."); } else { Console.WriteLine("Watch for black ice! Temp: {0}", temp); }

Outer if statement

Nested if statement

Quiz: Are there a missing braces?

34

Switch Statements

switch (myChoice) { case Democrat: Console.WriteLine("You voted Democratic."); break; case Republican: Console.WriteLine("You voted Republican."); break; case Progressive: Console.WriteLine("You voted Progressive."); break; }

switch on the value of myChoice

Execute case statements depending on value

Break out!

35

The Default Case

switch (myChoice) { case Democrat: Console.WriteLine("You voted Democratic.\n"); break; case Republican: Console.WriteLine("You voted Republican.\n"); break; case Progressive: Console.WriteLine("You voted Progressive.\n"); break; default: Console.WriteLine("You did not make a valid choice."); break; }

When will the default statements be executed?

36

Falling Through and Jumping Cases

case "NewLeft": Console.WriteLine( "The NewLeft members are voting Democratic."); goto case "Democrat";case "Democrat": Console.WriteLine("You voted Democratic.\n"); break;case "CompassionateRepublican": case "Republican": Console.WriteLine("You voted Republican.\n"); Console.WriteLine("Don't you feel compassionate?"); break;

Fall through case

Jump Case

37

Looping Statements

Execute statements repeatedly The number of time can depend on condition Types of loop

Use goto statementUse while loopUse for loop

38

Creating Loops with goto

int counterVariable = -10; repeat: Console.WriteLine("counterVariable: {0}",counterVariable);

++counterVariable;

if (counterVariable < 30) goto repeat;

The label

Increment the counter

Branch to label

Why is this type of loop not a good idea?

39

The while Loop

while (counterVariable < 10) { Console.WriteLine("counterVariable: 0}",counterVariable); counterVariable++; }

While the condition is true …

… execute the statements

40

The do … while Loop

do

{ Console.WriteLine("counterVariable:{0}",counterVariable);

counterVariable--;

}

while (counterVariable >0);The condition is now after the statements

What is the minimum number of times the statements will run?

41

The for Loop

for (int counter=100; counter>80; counter--) { Console.WriteLine( "counter: {0} ", counter); }

The counter variable changes on each iteration

What numbers will be output?

42

Break Out! for (int counter=0; counter<10; counter++) { Console.WriteLine("counter: {0} ", counter); if (counter == 5)

{ Console.WriteLine("Breaking out of the loop"); break; } }

If condition is met, break outWhat is the next

statement executed after a break out?

43

Continue a Loop from the Top

if (signal == "0") {continue;}

Start loop from top at next iteration

Can you think of an example where this be used?

44

Other Loops

for ( ; counter<10; counter++) No initialisation

for (int counter = 0; counter<10; ) No increment

for ( ;; ) No anything!

while (true) Always true(loop forever?)

45

Unit 3 Lab

1. To write statements to input two numbers and display the result

2. To write if …else statements to input three numbers and display the largest

3. To write switch statements to input a country and display its capital

4. To write looping statements that to display the list 10, 20, 30, 40 … 100

46

4. Operators

A symbol that takes an actionAssignment ( = )Mathematical ( +, -, *, / ) Increment and Decrement ( +=, -= )Relational ( >, >=, <, <=)Logical ( &&, ||, ! )

47

Assignment Operators (=)

int smallInt = 5;

smallInt = otherInt= 5;

Declare and assign

Multiple Assignments

48

Mathematical Operators

+ Add

- Subtract

* Multiply

/ Divide

% ModulusWhat is the order of precedence of these operators?

49

The Modulus Operator (%)

for (int counter=1; counter<=100; counter++) {

Console.Write("{0} ", counter);

if ( counter % 10 == 0 ) { Console.WriteLine("\t{0}", counter); } }

If the remainder after dividing by 10 is 0

What will be output?

50

Calculate and Reassign Operators

MySalary += 5000 Add 5000 to MySalary

MySalary -= 5000 Subtract 5000 from MySalary

MySalary *= 5000 Multiply MySalary by 5000

MySalary /= 5000 Divide MySalary by 5000

51

Increment and Decrement by 1

++ intB; Increment-- intB; DecrementintA = ++ intB; Increment then assign - prefixintA = -- intB; Decrement then assign - prefixintA = intB ++; Assign then increment - postfix

intA = intB --; Assign then decrement - postfix

52

Prefix and Postfix Operators

int original = 10; int result;

result = ++original; Console.WriteLine("After prefix: {0}, {1}", original,result);

result = original++; Console.WriteLine("After postfix: {0}, {1}",original,result);

Increment then assign

Assign then increment

What numbers are output?

53

Relational Operators

intA = 100; intB = 50;

intA == 100 Equals true

intA != 100 Not equals false

intA > intB Greater than true

intA >= intB Greater than or equal to true

intA < intB Less than false

intA <= intB Less than or equal to false

54

Logical Operators

x = 5; y = 7;

Name Operator Statement Result

And && (x==3) && (y == 7) False

Or || (x==3) || (y == 7) True

Not ! !(x==3) True

55

The Conditional Operator (?)

int maxValue = valueOne > valueTwo ? valueOne : valueTwo;

Condition

Assign valueOne if true Assign valueTwo if false

56

Operator PrecedenceintA = 5+7*3;

intA = (5+7)*3;

What’s the results?

Category Operators

1- Unary + - ! ( )

2- Multiplicative * / %

3- Additive + -

4- Relational < > <= <=

5- Logical && ||

57

Unit 4 Lab

1. To write statements using the multiplication operator to display the twelve-times table

2. To write statements to input two numbers and use logical operators to output if the result of multiplying them will be positive or negative

58

5. Object-Orientated Programming

What is OOP? Creating Models Classes and Objects Defining a Class Class Relationships The Three Pillars of OOP Analysis and Design

59

What is OOP?

Windows and web programs are vastly complex Rich graphical interfaces Complex business relationships Users interact with programs in many ways

Programmers refer to information about the problem they are solving as the problem domain

OOP is a technique for managing this complexity by defining objects from the problem domain

60

Characteristics of Objects

State The current conditions of an object, e.g. a customer

object’s state may include address & phone number. Capabilities

What the object can do that is relevant to the problem domain, e.g. buy an item, return an item …

Responsibilities The customer object is responsible for managing its own

address. No other object needs to know this.

61

Creating Models Humans are model builders Models are simplifications e.g. a road

atlas Good models hold information that is

relevant to the problem domain, no more & no less

Programming models contain metaphors to represent concepts, E.g. a window, a folder

A good OO design is an accurate model of the problem

62

Classes and Objects A class defines a new type of thing, e.g. a

car class A class defines the common characteristics,

e.g. every car has wheels, brakes … An object is an individual instance of a

class, e.g. a specific car object An object is just a thing

63

Defining a Class

A class definition contains members These describe the characteristics and

behaviour of objects of the classes type These members can be

Fields & Properties These hold the internal state of the object

Methods These do the work for the object

64

Defining a Classpublic class Cat{ private int weight; private String name;

public Cat(String name, int weight) {

this.name = name; this.weight = weight; }// Class code …}

Class definition

Fields

A method

65

Class Relationships Good OO design depends on establishing

relationships among classes Classes interact and relate in various

ways The simplest form of interaction is when a

method in one class calls a method in another

Some complicated classes are composed of other classes, e.g. an automobile is composed of wheels, an engine …

The automobile class is said to aggregate the simpler classes

Car

Engine Wheels

Gear Box Piston

66

The Three Pillars of OOP

Good OO design is built on three sturdy pillarsEach class is fully encapsulated to define its state Inheritance allows the definition of a hierarchical

relationship among classes Polymorphism allows a group of objects to be

treated in the same way

67

Encapsulation

Each class is discreet and self-contained The implementation of one class can be

changed without affecting other classes There is a clear separation between a classes:

Public interface (its contract with clients)Private implementation (how it does what it has

agreed)

68

Inheritance Inheritance allows a new class to be

derived from an existing class The new (derived) class inherits

characteristics from the existing (base) class

The inheritance relationship is referred to as an is-a relationship e.g. a violin is a stringed instrument

Inheritance allow the creation of a family of objects, e.g. a button is a control, but also a list box is a control

StringedInstrumentStringed

Instrument

ViolinViolin

Violin is derived from a base class

69

Polymorphism

Poly (many) – Morph (forms) Consider the controls class, that has derived

classes; buttons & list boxes These subclasses inherit a shared ability; the draw

method The draw method can be called for each subclass Each subclass knows how to implement the method

for itself (draw a button, draw a list box)

70

Analysis and Design

Analysis is researching the problem Design is actually planning the solution Analysis can take week or months for complex

problems Analysis includes

Determining the success factors Specifying the requirements (functional spec.)

Design Includes Imagining the classes and their inter-relationship Creating class diagrams using UML

71

6. Classes and Objects

First ask what does the class model Can I inherit from an existing base class What members does the class expose An object is an instance of a class Classes are reference types held on the stack

in memory

72

A Simple Class public class MyClass { public void SomeMethod(int firstParam, float secondParam) { Console.WriteLine( "Here are the parameters received: {0}, {1}", firstParam,

secondParam); } } public class Tester { static void Main() { int howManyPeople = 6; float pi = 3.14f; MyClass mc = new MyClass(); mc.SomeMethod(howManyPeople, pi); } }

73

Creating a Constructor

A constructorCreates an instance of a classPuts this in a valid stateThe compiler will implicitly provide (if not declared)Can provide with argumentsCan provide several overloaded versions of

constructorHas same name as class & no return type

74

Creating a Constructorpublic class Time { // private member variables int hour; int minute; int second;

// public method public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2}", hour, minute, second); }

// constructor public Time(int theHour, int theMinute, int theSecond) { hour = theHour; minute = theMinute; second = theSecond; } }

75

Others Clever Things with Objects

Initializer Initialize the value of a class member variable

int second = 30

The this keyword Refers to the current instance of an object

Public void SomeMethod(int hour){

this.hour=hour}

76

Access Modifiers

Determines availability of the class to clients public: visible to any client class protected: visible only to derived classes internal: visible only to classes in the same

assembly

[access-modifiers] class <identifier> [:base]{ class body }

77

Instance and Static Members

Instance MembersAssociated with instance of class btnUpdate = new Button(); btnUpdate.Draw();

Static MembersAssociated with class itself Button.GetButtonCount();

78

Instance and Static Memberspublic class Cat{ private static int instances = 0; private int weight; private String name;

public Cat(String name, int weight) { instances++; this.name = name; this.weight = weight; }

public static void HowManyCats() { Console.WriteLine("{0} cats adopted", instances); }

public void TellWeight() { Console.WriteLine("{0} is {1} pounds", name, weight); } }

79

Destroying Objects

Objects are destroyed by Garbage Collector To free unmanaged resources declare a

destructor (will be called by Garbage Collector)~MyClass(){}

Or, provide a Dispose() method & ask clients to callprotected override void Dispose( bool disposing )

80

Encapsulating Data with Properties

public int GetHour

get { return Hour; }

set { Hour =value; }

Declare a property that can be read from or written to

81

Unit 6 Lab

1. To write statements to define a class called Date that has a constructor and fields for year, month, day. Also define a method called DisplayTime() in the class.

2. To add an overloaded constructor to the Date class

3. To add properties (get & set) for the year, month, day to the Date class

82

7. Inside Methods

Several methods can have the same nameOverload method signature

Class data can be encapsulated with propertiesProvide clients controlled access to class state

Method can return multiple values by passing parameters by reference

83

Overloading Method Signatures

public Time(System.DateTime dt) { … }

public Time(int Year, int Month, int Date, int Hour, int Minute, int Second)

{ … }

public Time(int Year, int Month, int Date, int Hour, int Minute)

{ … }

Same method name

but a different number & type of parameters

84

Passing Parameters by Reference

public void GetTime(ref int h, ref int m, ref int s) { h = Hour; m = Minute; s = Second; }

t.GetTime(ref theHour, ref theMinute, ref theSecond);

Declare a method that takes parameters passed by reference

Now call the method with reference parameters

85

Creating a Two Tier ApplicationCreate the business tier

Create a new class library projectCreate a class to represent a business entity, say DateAdd properties that expose attributes, say year, month, dayAdd methods for business rules

Create the presentation tierCreate a new console application projectAdd a reference to the above class library projectCreate an object from classUse the object’s properties to access data itemsUse the object’s methods to perform business processes

86

Unit 7 Lab

To add a GetDate method to the Date class, using ref parameters for year, month, day. Test the method.

87

8. Debugging

A powerful tool to understand and fix code at runtime

Setting a breakpoint Stepping through code Using the debug windows view variables The call stack

88

Setting a Breakpoint

Click here to set breakpoint

Code is paused at runtime

89

Stepping through Code

Step into (F11) Execute the current line of code

Step over (F10) Execute the current line of code, but skip procedures

Step out (Shift F11) Resume execution from calling procedure

The values of variables can be seen by hovering mouse pointer over them

90

Using the Debug Windows

Immediate Window Evaluates expressions, executes statements, print variable

values Locals Window

View ( and modify) variables within local scope Watch window

Add variables to watch their values Call Stack

Show the calling methods of the current method

91

9. Inheritance

Derived classes are defined from a base class The derived class specialises the base class The derived class inherits all members The derived class can also implement its own

version of the base class

92

Inheritance

93

Inheritance Hierarchy

… inherits from …

94

Implementing Inheritance

Define Base Classpublic class BaseForm : System.Windows.Forms.Form

Define Derived Classpublic class AddressForm : BaseForm

Use Derived Class in Client ClassAddressForm af = new AddressForm();af.Show();

95

Inside Inheritance

Calling the Base Class Constructorpublic AddressForm():base()

Replacing Base Methodsprotected new void OnCustomerLocate()

Calling Base Methods

base.OnCustomerLocate

96

Polymorphism

Powerful aspect of inheritance Poly (many) – Morph (forms) Example: T-Mobile supplies many handsets

Each handset “instance” knows how to ringWhen the ring command is sent, the handset

obeys in its own way

97

Creating a Polymorphic Method

In Basepublic class Windowpublic virtual void DrawWindow()

In Derived Classpublic class ListBox : Windowpublic override void DrawWindow()

98

Calling the Polymorphic Method

In Client Class

Window[] winArray = new Window[2]; winArray[0] = new Window(); winArray[1] = new ListBox();

//Loop thru array calling polymorphic method for (int i = 0;i < 2; i++) { winArray[i].DrawWindow(); }

99

Other Kinds of Methods

The derived class must implement a base methodabstract public virtual void DrawWindow()

The derived class cannot override a base methodsealed public virtual void DrawWindow()

100

Unit 9 Lab

To define a class called Control, with a constructor and a DrawControl() method. Create a class called TextBox that inherits from Control and replaces the DrawControl method. Test the TextBox class

101

10. Operator Overloading

What is Operator Overloading Using the Operator Keyword Creating Useful Operators The Equals Operator Conversion Operators

102

What is Operator Overloading

C# allows new classes to have the functionality of built-in types

This includes the ability to define operators for a new class

For example: + and = operators may be defined for a Fraction class

This is a better alternative to creating a Fraction.Add() method

103

Using the operator Keyword

C# operators are static methods To create a new operator combine the

operator keyword with the symbol This operator (+) will take two parameters of

type Fraction & return a Fraction

public static Fraction operator+(Fraction lhs, Fraction rhs)

104

Defining an Operatorpublic Fraction(int numerator, int denominator) { this.numerator=numerator; this.denominator=denominator; }public static Fraction operator+(Fraction lhs, Fraction rhs) {

if (lhs.denominator == rhs.denominator) { return new Fraction(lhs.numerator+rhs.numerator, lhs.denominator); }

int firstProduct = lhs.numerator * rhs.denominator;int secondProduct = rhs.numerator * lhs.denominator;

return new Fraction( firstProduct + secondProduct,lhs.denominator * rhs.denominator ); }

Create the Fraction class

Create the + operator

105

Creating Useful Operators

Operator overloading can make code more intuitive when new classes behave like built in types

But, resist the temptation to overuse For example: the incremental operator (++)

could cause a pay increase to an Employee class

This may be confusing to clients of this class

106

The Equals Operator

The root Object class offers an Equals() method

If the equals operator (==) is overridden for a Fraction, it is recommended that the Equals() method is also overridden

This means that Equals() can be called on two objects Fractions

107

Overloading the Equals Method

public override bool Equals(object o) { if (! (o is Fraction) ) { return false; } return this == (Fraction) o; }

Test if the parameter is an object

Use the overloaded == to test for equality

108

Overloading the == and != Operators

public static bool operator==(Fraction lhs, Fraction rhs) { if (lhs.denominator == rhs.denominator && lhs.numerator == rhs.numerator) { return true; } return false; }

public static bool operator!=(Fraction lhs, Fraction rhs) { return !(lhs==rhs); }

Test for equality of Fractions

Test for inequality by delegating to the == operatorWhy is it a good idea

to create both the == & != operators?

109

Using the == and != Operators

if (f4 == f3) { Console.WriteLine("f4: {0} == F3: {1}", f4.ToString(), f3.ToString()); }if (f4 != f2) { Console.WriteLine("f4: {0} != F2: {1}", f4.ToString(), f2.ToString()); }

Test for equality

Test for inequality

Where is the ToString() method implemented?

110

Conversion Operators

An int data type can be implicitly converted to a long

Also, a long data type can be explicitly converted to an int

Similarly, operators can be defined for the Fraction class to convert from:a Fraction to an integer e.g. 9/4 becomes 2 an integer to a Fraction e.g. 15 becomes 15/1

111

Creating Conversion Operators public Fraction(int wholeNumber) { numerator = wholeNumber; denominator = 1; }

public static implicit operator Fraction(int theInt) {

return new Fraction(theInt); }

public static explicit operator int(Fraction theFraction) { return theFraction.numerator /theFraction.denominator; }

Constructor taking a whole number

Implicitly converting int to fraction

Explicitly converting Fraction to int

112

Using Conversion Operators

Fraction f1 = new Fraction(3,4); Fraction f2 = new Fraction(2,4); Fraction f3 = f1 + f2;

Fraction f4 = f3 + 5; int truncated = (int) f4;

Convert int to fraction implicitly

Convert fraction to int explicitly

113

Unit 10 Lab

To define a class called Fraction, with a constructor and a ToString() method. Create a subtraction operator (-) using operator overloading. Test the operator.

114

11. Structs

Lightweight alternative to classes Like classes they can define

Constructors, properties, methods and fields But they do not allow

Inheritance or destructors They are value not reference types Use for small, simple objects

115

Defining a Struct public struct Location {

private int xVal; private int yVal;

public Location(int xCoordinate, int yCoordinate) { xVal = xCoordinate; yVal = yCoordinate; }

The struct has private data

It has a constructor

116

Defining a Struct 2 public int XVal { get { return xVal; } set { xVal = value;} }

public int YVal { get { return yVal; } set { yVal = value; } }

public override string ToString() { return (String.Format("{0}, {1}", xVal,yVal)); } } // end struct

The struct has two properties …

… and a method

117

Using a Struct

Location loc1 = new Location(200,300);

Console.WriteLine("Loc1 location: {0}", loc1);

Location loc2 = new Location(); Console.WriteLine("Loc2 location: {0}", loc2);

myFunc(loc1);

Create an instance of the struct

Display the values in the struct

Invoke the default constructor

Pass the struct to a method

What is output when the default constructor is used?

118

Unit 11 Lab

To define a struct called Colour, with a constructor and a ToString() method. This will hold three numbers to represent the red, green and blue component of the colour. Test the Struct.

119

12. Interfaces

Implementing an Interface Implementing More Than One Interface Casting to an Interface The is and as Operators Extending Interfaces Combining Interfaces

120

What is an Interface

Allows the designer to specify the behaviours an object must implement

The interface describes only which properties, methods and events will exist

The class using the interface agrees to implement all of these

121

Implementing an Interface

interface IStorable { void Read(); void Write(object obj); int Status { get; set; } }

Define the interface

Define its properties and methods

122

Create a Class to Implement the Interface

public class Document : IStorable {

public void Read() {

Console.WriteLine( "Implementing the Read Method for IStorable"); }

public void Write(object o) { Console.WriteLine( "Implementing the Write Method for IStorable"); }

public int Status { get{ return status; } set{ status = value; } }

Implement the Read method

Implement the Write method

Implement the Status property

123

Test the Implementing Class

Document doc = new Document("Test Document"); doc.Status = -1; doc.Read(); Console.WriteLine("Document Status: {0}", doc.Status);

Use the interface’s methods and property

124

Implementing More Than One Interface

Classes can derive from only one base class But, classes can implement any number of

interfaces This provides added flexibility for class

designers

125

Implementing Two Interfacesinterface IStorable { void Read(); void Write(object obj); int Status { get; set; } }interface ICompressible { void Compress(); void Decompress(); }

public class Document : IStorable, ICompressible

Here's the new interface

Document implements both interfaces

126

Casting to an Interface

In some cases you don’t know the type of the class You only know the interface it implements You can then cast the object to that interface type You can then use the object’s members through the

interface type Access through an interface allows you to treat the

interface polymorphically

127

Casting to an Interface 2

public class Document : IStorable

Document doc = new Document("Test Document"); IStorable isDoc = (IStorable) doc;isDoc.Read();

The Document class Implements the IStorable interface

Cast the doc object to the IStorable type

What happens if the class does not implement the interface?

128

The is Operator

Document doc = new Document("Test Document");

if (doc is IStorable) { IStorable isDoc = (IStorable) doc; isDoc.Read(); } else { Console.WriteLine("Could not cast to IStorable"); }

Only cast if does

Does the object implement interface?

129

The as Operator

This combines the is evaluation and the cast operation

If the cast is not valid the operator returns null The as operator is more efficient than the is

operator

130

The as Operator 2

Document doc = new Document("Test Document"); IStorable isDoc = doc as IStorable; if (isDoc != null) { isDoc.Read(); } else { Console.WriteLine("Could not cast to IStorable"); }

Cast using as, then test for null

131

Extending Interfaces

Add new members Modify how existing members work For example

Extend ICompressible with the new interface ILoggedCompressible

Add one additional method to ILoggedCompressible

132

Extending Interfaces 2interface ICompressible { void Compress(); void Decompress(); }interface ILoggedCompressible : ICompressible { void LogSavedBytes(); }

public class Document : ILoggedCompressible

public void LogSavedBytes() { Console.WriteLine("Implementing LogSavedBytes"); }

Extend ICompressible to log the bytes saved

Define ICompressible interface

Document implements ILoggedCompressible

Now implement that extra method

133

Combining Interfaces

New interfaces can be created by adding existing interfaces

New members can be added to the new interface

134

Combining Interfaces 2

interface IStorableCompressible : IStorable, ILoggedCompressible { void LogOriginalSize(); }

public class Document : IStorableCompressible

Add two existing interfaces

Add method

Class that will implement the interface

135

Unit 12 LabTo define an interface called IClient. This includes properties for name and address details and a method called Order. Create a class called Customer that implements the interface and adds an additional method. Test the Customer class.

136

13. Arrays

An array is a collection of objects of the same type Declaring Arrays Accessing Array Element The foreach Statement Multidimensional Arrays System.Array Indexers

137

A One Dimensional Array

0 1 2 3 4 5 6 7

Like a set of pigeon holes

Each pigeon hole can hold the same kind of object

Each pigeon hole is accessed by its number: 0, 1, 2 …

138

Declaring Arrays

int[] intArray;Employee[] empArray;

intArray = new int[5];empArray = new Employee[3];

Declare arrays

Initialise arrays with 5 & 3 elements

What are the default values of the array elements?

139

Declaring Arrays 2

int[] intArray = { 2, 4, 6, 8, 10 };Employee[] empArray ={ new Employee(5), new Employee(7), new Employee(9) };

int[] intArray = new int[5];Employee[] empArray = new Employee[3];

Declare and initialise arrays

Alternatively, declare, initialise and populate arrays

The default values for integers are 0, and for objects null

140

Accessing Array Elements

intArray[3];

This returns the 4th element since indexing starts at 0

for (int i = 0;i<empArray.Length;i++) { empArray[i] = new Employee(i+5); Console.WriteLine(empArray[i].empID); }

Populate the Employee array using a loop

141

The foreach Statement

foreach( int theInt in intArray ){

Console.WriteLine(theInt.ToString());}

Loop through all items in the array

142

The params keyword

public void DisplayVals(params int[] intVals) { foreach (int i in intVals) { Console.WriteLine("DisplayVals {0}",i); } }

The method takes a variable number of integers as a parameter

int [] explicitArray = new int[4] {5,6,7,8}; DisplayVals(explicitArray);

Call method passing an array

143

Multidimensional Arrays

3,2

Col. 0 Col. 7

Row 1

Row 2

Row 3

Row 4

Row 5

144

Declaring 2D Arrays

int[,] boxArray = new int[2,3];

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

Or declare and populatethe array

Declare the array

145

Loop through 2D Array

for (int i = 0;i < rows;i++){

for (int j = 0;j<columns;j++){Console.WriteLine("rectangularArray[{0},{1}] = {2}",

i,j,rectangularArray[i,j]);}

}

Inner loop

Outer loop

Which is iterated through first, the rows or the columns?

146

Jagged Arrays (Array of Arrays)

int[][] jaggedArray = new int[rows][];

jaggedArray[0] = new int[3]; jaggedArray[1] = new int[7]; jaggedArray[2] = new int[9];

Declare the rows of various lengths

jaggedArray[0][3] = 15; jaggedArray[1][1] = 12; jaggedArray[2][1] = 9;

Fill some elements

147

System.Array Class

Arrays are implemented with the System.Array class, which provides these useful methods: Clear() Copy() Reverse() Sort() Length() Rank()

148

Indexing Classes

Some classes can act like arrays For example, a class list ListBoxTest can act

like an array of the strings it contains An indexer allows a class to be treated like an

array:ListBoxTest[3];

149

Indexing Classespublic class ListBoxTest{ public string this[int index] { get { if (index < 0 || index >= strings.Length) { // handle bad index } return strings[index]; } set { strings[index] = value; } }

Allow array-like access

Set value in internal array

Get value from internal array

150

Testing an Indexed Class

// create a new listbox and initialize ListBoxTest lbt = new ListBoxTest("Hello", "World");

// add a few strings lbt[1] = “Who” lbt[2] = “are"; lbt[3] = “the";

lbt[4] = “developers";

// access all the strings for (int i = 0; i<lbt.GetNumEntries(); i++) { Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]); }

151

Unit 13 Lab

To create a two dimensional array of integers holding the twelve-times table. Use looping statements to populate the array and display its elements

152

14. Collection Interfaces and Types

The Collection Interfaces Array Lists Queues Stacks

153

What Are Collections?

A collection holds a group of similar objects An array is the simplest type of collection The .Net Framework provides built-in collection types The .Net Framework holds collection classes in

System.Collections Each type provides standard methods for accessing

& manipulating the collection’s content

154

The Collection Interfaces Collections implement interfaces that provide their

characteristics Custom classes can also implement these interfaces For example, create a custom class ListBoxTest that holds

the strings it displays The class can implement the collection interfaces to provide

standard methods for: Indexing Sorting Enumeration

155

The Collection Interfaces 2Interface Purpose

IEnumerable Enumerate a through a collection using the foreach statement

IEnumerator Iterates over collection & supports the foreach statement

ICollection Implemented by all collections

IComparer Compares two objects: used for sorting

IList Used by collections that can be indexed

IDictionary For key/value collections such as HashTable and SortedList

IDictionaryEnumerator Iterates over dictionary & supports the foreach statement

156

Array Lists

An array list is like an array But, its size is dynamically increased as

required It provides many useful properties and

methods

157

Array List MembersMethod or Property

Purpose

Capacity() The number of elements the ArrayList can hold

Count() The current number of ArrayList elements

Item() Get or set the ArrayList elements at the specified index

Add() Adds an object at the end of the ArrayList.

Insert() Inserts an element into the ArrayList at the specified index.

RemoveAt() Removes the element at the specified index of the ArrayList

Reverse() Reverses the order of the elements in the ArrayList or a portion of it

Sort() Sort alphabetically the array list

ToArray() Copy the elements of the ArrayList to a new array

158

Array List Example

ArrayList empArray = new ArrayList();ArrayList intArray = new ArrayList();

for (int i = 0;i<5;i++) { empArray.Add(new Employee(i+100)); intArray.Add(i*5); }

foreach (int i in intArray) { Console.Write("{0} ", i.ToString()); }

foreach(Employee e in empArray) { Console.Write("{0} ", e.ToString()); }

Populate the ArrayLists

Print the ArrayLists’ members

159

Queues

Queues are a first-in, first-out collection (FIFO) Imagine a queue at a bus stop Queues are good for managing limited

resources e.g. messages

160

Queues Members

Method or Property

Purpose

Count() Gets the number of elements in the Queue

Clear() Remove all objects

Contains() Determines if an element is in the Queue

CopyTo() Copies elements to a one-dimensional array

Dequeue() Remove and return an object at start of the Queue

Enqueue() Add an object at end of the Queue

Peek() Returns an object at start of the Queue without removing it

ToArray() Copy the elements of the Queue to a new array

161

A Queue ExampleQueue intQueue = new Queue();for (int i = 0;i<5;i++) { intQueue.Enqueue(i*5); }Console.Write("intQueue values:\t" );DisplayValues( intQueue );

Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue() );DisplayValues( intQueue );

Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue() );DisplayValues( intQueue );

Console.WriteLine("\n(Peek) \t{0}", intQueue.Peek() );DisplayValues( intQueue );

Populate the Queue

Remove elements

View but do not remove elements

162

Displaying Queue Values

public static void DisplayValues( IEnumerable myCollection ) { IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "{0} ",myEnumerator.Current ); Console.WriteLine(); }

The parameter type is IEnumerable

Iterate thought items of the collection

How does the IEnumerable interface work?

163

Stacks

Queues are a last-in, first-out collection (LIFO) Imagine a stack of dishes on a buffet table The principal methods for adding and

removing items are Push() and Pop()

164

Stack Members

Method or Property

Purpose

Count() Gets the number of elements in the Stack

Clear() Remove all objects

Contains() Determines if an element is in the Stack

CopyTo() Copies elements to a one-dimensional array

Pop() Remove and return an object at top of the Stack

Push() Add an object at top of the Stack

Peek() Return an object at top of the Stack without removing it

ToArray() Copy the elements of the Stack to a new array

165

A Stack Example

Stack intStack = new Stack();for (int i = 0;i<8;i++) { intStack.Push(i*5); }

Console.WriteLine( "\n(Pop)\t{0}", intStack.Pop() );

Console.WriteLine( "\n(Peek) \t{0}",intStack.Peek() );

DisplayValues( intStack );

Declare & populate the stack

Remove an element

View an element

Display all elements

166

Displaying Stack Values

public static void DisplayValues( IEnumerable myCollection ) { foreach (object o in myCollection) { Console.WriteLine(o); } }

Iterate thought items of the collection

The parameter is of type IEnumerable

167

Unit 14 Lab

1. To create an ArrayList of integers. Use looping statements to populate this with multiples of 10. Experiment with the ArrayLists methods, including the Sort(), Reverse() and Clear() methods.

2. To create a Queue of integers. Use looping statements to populate this. Experiment with the Queues methods, including the Dequeue(),Enqueue () and Peek() methods.

3. To create a Stack of integers. Use looping statements to populate this. Experiment with the Stacks methods, including the Pop(),Push () and Peek() methods.

168

15. Strings

Creating Strings Manipulation Stings

Concatenating StringsCopying StringsSplitting Strings

The StringBuilder Class Regular Expressions

169

What Exactly are Strings?

Strings hold a variable number of characters C# provides the built in string type This aliases the System.String .Net class Strings are objects with methods for:

ConcatenationComparisonExtracting sub-stings

170

Creating Strings

string s1 = "abcd";

string s2 = "ABCD\n";

string s3 = "ABCD\t EFGH";

Declare a string

Declare a string with an escape character for a new line

Use an escape character for a tab

string s4 = myInteger.ToString();

Use the ToString() method

171

Comparing Stringsstring s1 = "abcd";string s2 = "ABCD";int result;

result = string.Compare(s1, s2);Console.WriteLine("compare s1: {0}, s2: {1}, result: {2}\n", s1, s2, result);

result = string.Compare(s1,s2, true);Console.WriteLine("Compare insensitive. result: {0}\n", result);

Hold the results of comparisons

Compare two strings, case sensitive

Compare, case insensitive

If result is negative, the first value is smallerIf result is positive, the first value is biggerIf result is zero, the values are equal

172

Concatenating Strings

string s3 = string.Concat(s1,s2);

string s4 = s1 + s2;

Concatenation method

Use the overloaded + operator

173

Copying Strings

string s5 = string.Copy(s2);

string s6 = s5;

Copy method

Use the overloaded = operator

174

Test for Equality

if s6.Equals(s5)…;

if string.Equals(s6,s5)…;

if s6 == s5 …;

Use the member method

Use the static method

Use the overloaded == operator

175

Other Useful Methods

Method Return value or actions3.Length The number of characters in s3

s3[4] The 5th character of s3

s3.EndsWith("Training") True if s3 ends with “Training”

s3.IndexOf("Training") The index of the substring

s3.Insert(101,“Excellent “) Insert the substring at 101st character

176

Splitting Strings 1string s1 = "One.Two;Three Four";

const char Space = ' ';const char Comma = ','; const char Stop = '.';const char SemiColon = ';';

char[] delimiters = new char[] {

Space,Comma,

Stop, SemiColon };string output = "";int ctr = 1;

A string to split

The string delimiters

Put the delimiters in an array

177

Splitting Strings 2

String[] resultArray = s1.Split(delimiters);foreach (String subString in resultArray) { output += ctr++; output += ": "; output += subString; output += "\n"; }Console.WriteLine(output);

Split the string

Iterate over the resulting array of strings

178

The StringBuilder Class

The class System.Text.StringBuilder can be used for creating and modifying string

StringBuilder is mutable, when an instance is modified, the actual string is modified, not a copy

StringBuilder is more efficient than String because only a single string object is created

179

The StringBuilder Class 2

StringBuilder output = new StringBuilder();int ctr = 1;

foreach (string subString in s1.Split(delimiters)) { output.AppendFormat("{0}: {1}\n",ctr++,subString); }Console.WriteLine(output);

Use the StringBuilder class to build the output

Split the string

AppendFormat appends a formatted string

180

StringBuilder Methods

AppendFormat appends a formatted string

Method ExplanationAppend() Append string at end of current string

AppendFormat() Append formatted string at end of current string

Insert() Insert string at specified position

Length () Retrieve or assign the length of the string

Remove() Remove specified characters

Replace() Replace all specified characters with new characters

181

Regular Expressions

A powerful language to describe and manipulate text

Uses pattern matching to compare string with wildcards

Applying a regular expression to a string can returnA substringA modification of the original

182

Regular Expressions 2string s1 = "One,Two,Three Liberty Associates, Inc.";Regex theRegex = new Regex(" |, |,");StringBuilder sBuilder = new StringBuilder();int id = 1;

foreach (string subString in theRegex.Split(s1)) { sBuilder.AppendFormat({0}: {1}\n", id++, subString); }Console.WriteLine("{0}", sBuilder);

Define the Regular Expression

Spit the string using the Regular Expression

183

Unit 15 Lab

To input a string representing a URL. Experimenting with extracting substrings and splitting the URL using the dot (.) and forward slash (/) separators.

184

16. Throwing and Catching Exceptions

Exception Handling The throw Statement The try and catch Statements How the Call Stack Works The finally Statement Dedicated catch Statements

185

Exception Handling

C# handles errors and abnormal conditions with exceptions

Exceptions can be thrown byA throw statementA .Net Framework classThe operating system (e.g. a security violation)

Exceptions are caught by code in a catch block (i.e. an exception handler)

186

The Exception Class

All exceptions are of type System.Exception or derived from this

Exceptions types includeArgumentNullException InvalidCastExceptionOverflowException

Exception objects provide information on what went wrong (message, help file, source …)

187

Try and Catch Statements

public void Func1(){Console.WriteLine("Enter Func1..."); try { Console.WriteLine("Entering try block..."); Func2(); Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine("Exception caught and handled!"); } Console.WriteLine("Exit Func1...");}

Test for errors in try block

Run statement in catch block if an error occurs

188

Searching for an Exception Handler

Statement1

Statement2

MethodA()

Statement3

Statement4

End method

Statement1

Statement2

MethodB()

Statement3

Statement4

End method Statement1

Statement2

Statement3

Statement4

End method

Method A

Method B

Call

Search for handler

Call

Search for handler

Main

Exception thrown !!

Unwind the call stack looking for a handler

If no exception handler, then the CLR handles the exception

189

The throw Statement public void Run() { Console.WriteLine("Enter Run..."); Func1(); Console.WriteLine("Exit Run..."); } public void Func1() { Console.WriteLine("Enter Func1..."); Func2(); Console.WriteLine("Exit Func1..."); } public void Func2() { Console.WriteLine("Enter Func2..."); throw new System.Exception(); Console.WriteLine("Exit Func2..."); }

Throw an exception

The exception is unhandled so the program terminates

190

How the Call Stack Works public void Run() {

Func1(); } public void Func1() { try {

Func2(); }

catch { Console.WriteLine("Exception caught and handled!"); }

} public void Func2() { Console.WriteLine("Enter Func2..."); throw new System.Exception(); Console.WriteLine("Exit Func2..."); }

throw in Func2

catch in Func1

Will this statement run?

191

Creating Dedicated catch Statements

So far we have used a generic catch statement The catch statement can trap specific

exceptions Multiple catch statements can trap different

exceptions

192

Creating Dedicated catch Statements 2try { double a = 5; double b = 0; DoDivide(a,b) }

catch (System.DivideByZeroException) { Console.WriteLine("DivideByZeroException caught!"); } catch (System.ArithmeticException) { Console.WriteLine("ArithmeticException caught!"); }

catch { Console.WriteLine("Unknown exception caught"); }

The most derived exception type is first

The generic exception type is last

Why are the catch statements in this order ?

193

The finally Statementtry { double a = 5; double b = 0; DoDivide(a,b) }

catch (System.DivideByZeroException) { Console.WriteLine("DivideByZeroException caught!"); }

catch { Console.WriteLine("Unknown exception caught"); }

finally { Console.WriteLine(“close files here"); }

This statement must execute

What is another way of making this statement always run ?

194

Exception Class Methods and Properties

Member ExplanationSource The method that raised the exception

Message Information about the exception

Helplink Link to a help file

StackTrace Method calls that lead to the exception

InnerException The exception that caused the current exception

195

Using the Exception Class

DivideByZeroException e = new DivideByZeroException(); e.HelpLink ="http://www.la.com"; throw e;

catch (System.DivideByZeroException e) { Console.WriteLine("\nDivideByZeroException! Msg: {0}",e.Message); Console.WriteLine("\nHelpLink: {0}", e.HelpLink); Console.WriteLine("\nHere's a stack trace: {0}\n",.StackTrace); }

Set exception property

Display exception properties

196

Unit 16 Lab

To divide two integers and add exception handling with dedicated catch statements to create division by zero and other exceptions. Include a finally statement.

197

17. Delegates and Events

Robin Cook has died Tony Blair is not available

Define in advance what authority to delegate Funeral Attendances

and what “parameters” are passed Condolences and flowers

Delegate the task at “runtime” John Prescott attends the funeral

So what are delegates?

198

Delegates in C#

A delegate encapsulates a methodhas a specific return type & parameter list is instantiated with by passing a method as parametercan call the delegated method at runtime

199

Using Delegates

Define the delegatePublic delegate int WhichIsFirst(object obj1, object obj2);

Instantiate the delegate with a methodWhichIsFirst theStudentDelegate = new WhichIsFirst(WhichStudentComesFirst);

Call the delegated methodi= theStudentDelegate(objJohn, objFred);

200

Multicasting Delegates

Create a single delegate that calls multiple methods

Combine delegates with the + or += operators

myMulticastDelegate = Writer + Logger;

201

Multicasting Delegates// Define delegatepublic delegate void StringDelegate(string s);

// Define two methodspublic static void WriteString(string s) { …}public static void LogString(string s) {…}

// Define and instantiate two StringDelegate objects.StringDelegate Writer, LoggerWriter = new StringDelegate(WriteString);Logger = new StringDelegate(LogString);

//Multicast the delegatemyMulticastDelegate = Writer + Logger;

//Call the two delegated methods myMulticastDelegate(“log this string")

202

Events in C#

An object publishes a set of events Other classes can subscribe to these events For example, GUI control classes publish:

Mouse events Keyboard events

The publishing class also defines delegates The subscribing class implements these delegates

203

Events and Delegates

this.button1.Click

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

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

Event

Instantiate Delegate

Event Handler

204

Coupling Delegates to Event Handlers

linkLabel1.MouseEnter += new EventHandler(Bigger);linkLabel2.MouseEnter += new EventHandler(Bigger);linkLabel3.MouseEnter += new EventHandler(Bigger);

Delegates Event Handlers

205

Unit 17 Lab

To create a class Pair and include a delegate WhichisFirst, a constructor, and methods called Sort() and ReverseSort(). These methods take as a parameters an instance of the WhichisFirst delegate. To test the class create a Dog class. This implements methods that can be encapsulated by the delegate.

206

18. Generics

New feature of C# Version 2.0 and the CLR Generics allow a type parameter for classes and

methods Specification of the type is deferred to instantiation

at runtime Generic classes may be constrained to hold only

certain types of data Generics are most commonly used with collections

207

Using Generics

// Declare the generic class public class class MyList<T> { ....// }

// Declare a list of type MyList<int> list1 = new MyList<int>();

// Declare a list of type string MyList<string> list2 = new MyList<string>();

// Declare a list of type MyClass MyList<MyClass> list3 = new MyList<MyClass>();

208

The Reason for Generics

An ArrayList can hold objects of any type All objects are cast to the System.Object root class But, the overheads of casting will degrade performance Also, there is no way at compile time to prevent invalid

assignments, like:

arrayList1(9) =“A string”;int myInt = arrayList(9);

209

The Benefits of Generics

using System.Collections.Generic;

List<int> list1 = new List<int>();

list1.Add(3);

list1.Add("It is raining in the South West");

Import the Generic .Net class

Declare a list using the type parameter

Add element without casting or boxing

Generate compile-time error!

210

Parameter Constraints

When defining generic classes restriction can be placed on the type parameters

Theses restrictions are called constraints They are specified using the where keyword in

the class definition

211

Parameter ConstraintsConstraint Explanationclass MyList<T> where T: struct

The type argument must be a value type

class MyList<T> where T: class

The type argument must be a reference type

class MyList<T> where T: new()

The type argument must have a public parameterless constructor

class MyList<T> where T: <base class name>

The type argument must be or derive from the specified base class

class MyList<T> where

T: <interface name> The type argument must be or implement the specified interface

212

Generic Class Inheritance

A generic class, like any other, can be created by inheriting from a base class

The base class can be: A concrete type

class Node<T> : BaseNode A closed constructed type

class Node<T> : BaseNode<int> An open constructed type

class Node<T> : BaseNode<T>

213

Inheriting from Generic Classes

Non-generic (concrete) classes can inherit from closed constructed (generic) base classes class Node : BaseNode<int> //No error

But, not from open constructed (generic) classes class Node : BaseNode<T> //Generates an error

Because, there is no way at run time to supply the type argument required to instantiate the base class

214

Creating Generic Methodsvoid Swap<T>( ref T lhs, ref T rhs){ T temp; temp = lhs; lhs = rhs; rhs = temp;}

int a = 1;int b = 2;Swap<int>(ref a, ref b);

Swap(ref a, ref b);

A generic method with a type parameter

Calling the method using the type parameter

Or, calling the method inferring the type parameter

215

Unit 18 Lab

Experiment with creating generic classes and methods

Unit 19:

New Language Features in C#

New Language Features in C# 3.0 • Implicit Typing

• Anonymous Types

• Object and Collection Initialisers

• Extension Methods

• Partial Methods

• Lambda Expressions

Implicit Typing• The compiler determines the data type of variable

• The data type is not a variant

• The var keyword is used

• The initialiser cannot be null

var a = 5; Console.WriteLine("a"); Console.WriteLine("Variable type "+ a.GetType());

Anonymous Types

• The compiler creates a nameless class

• There is an inferred class definition

• The properties are set in the braces

var captain = new { FirstName = "Jamie", LastName = "Cooke" }; Console.WriteLine(captain.FirstName + " " + captain.LastName);

Object and Collection Initialisers

• Initialise an object by setting its properties inline

• Initialise a collection using multiple object initialisers

Person p = new Person{ Name = "Jamie", Age = 50 };

Person[] people = { new Person { Name="Allen Frances", Age=11}, new Person { Name="Burke Madison", Age=50}, new Person { Name="Connor Morgan", Age=59},

};

Extension Methods

• Extend a class by adding a method

• But put the method in another class

• This is usefully if you do not have the source code of the first class

• The methods first parameter's type is the original class

• Extensions methods are used extensively with LINQ queries

• LINQ provides extension methods for the IEnumerable & IQueryable classes that are used in queries

Extension Methods - Part II//The Money class has a property & a method public class Money

{ … }

//Add an extension method to the Money class public static class MoneyExtension {

public static void AddToAmount(this Money money, decimal amountToAdd)

{ money.Amount += amountToAdd; } } …

//Test the extension method Money m = new Money(); m.AddToAmount(10);

Partial Methods

• Partial classes allow the class definition to be contained in several files

• Partial methods allow a method to be implemented and called in a partial class

• The method implementation can be in one file and the call in another file

Partial Methods - Part II//First part of partial class partial class PartialMethods { static void Main() { Do(); } static partial void Do(); }//Second part of partial class, could be in 2nd file partial class PartialMethods { //Partial method implementation static partial void Do() { Console.WriteLine("Do some work");

} }

Lambda Expressions

• Anonymous methods provide a concise syntax for creating delegates

• The method is implemented in a block of code

DelegateTest anonDel = delegate(string param) {

param += " and this was added"; return param; };

Lambda Expressions – Part II

• Lambda expression simplify the syntax for creating anonymous methods

• Lambda expressions are used extensively with LINQ queries

//Instantiate the delegate using the lambda syntax DelegateTest anonDel2 = param => {

param += " and this was added"; return param; };

Console.WriteLine(anonDel2("Start of string"));

227

SummaryUnit Topic1. Getting Started with C#2. C# Language Fundamentals3. Branching4. Operators5. Object-Orientated Programming6. Classes and Objects7. Inside Methods8. Debugging9. Inheritance and Polymorphism

228

SummaryUnit Topic10. Operator Overloading11. Structs12. Interfaces13. Arrays14. Collection Interfaces and Types15. Strings16. Throwing and Catching Exceptions17. Delegates and Events18. Generics19. New Language Features

229

Contact

David Ringsell MCPD More courses and tutorials: www.talk-it.biz david@talk-it.biz

top related