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
2. Free .Net & SQL Server Web Tutorials
web and windows development
programming in VB and C#
database development
object orientation
http://talk-it.biz/category/tutorials
3. Course Content
Unit Topic
1. Getting Started with C#
2. C# Language Fundamentals
3. Branching
4. Operators
5. Object-Orientated Programming
6. Classes and Objects
7. Inside Methods
8. Debugging
9. Inheritance and Polymorphism
3
4. Course Content 2
Unit Topic
10. Operator Overloading
11. Structs
12. Interfaces
13. Arrays
14. Collection Interfaces and Types
15. Strings
16. Throwing and Catching Exceptions
17. Delegates and Events
18. Generics
19. New Language Features
4
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
5
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
7
8. Why C# and not VB
Syntax more like C++ and Java
Syntax very concise
Designed for object orientation
Started with a clean slate
Everything is an object
Microsoft are evolving language
8
10. C# Goals
Safe
Find bugs early in development process
Simple
Few keywords
Internet Centric
Designed for developing web programs
Hi Performance
Designed for industrial strength programming
10
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
11
12. Overview of .Net
Visual
Basic C++ C# Perl J# …
XML Web Services User Interface
ASP.NET
ADO.NET: Data and XML
.NET Framework Class Library
Common Language Runtime
COM+
Message
(Transactions, Partitions, IIS WMI
Queuing
Object Pooling)
Win32
12
13. 2. C# Language Fundamentals
Data Types
Numeric Types
Non-Numeric Types: char and bool
Variables
Definite Assignment
Constants
Strings
Statements
13
14. Data Types
Common C# intrinsic Type Size in Bytes
data types
byte 1
bool 2
int 4
long 8
float 4
double 8
decimal 12
14
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
15
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
16
17. Non-Numeric Types: char and bool
char
Holdsjust a single character
Can hold:
Simple character („A‟)
Unicode character (u0041)
Escape character („n‟)
bool
Holds true or false in one byte
17
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?
18
19. Declaring Constants
const int FreezingPoint = 32; // degrees Farenheit
const int BoilingPoint = 212;
Why would you create
constants?
19
20. Declaring Enumerations
An enumeration is a set of named constants
// declare the enumeration
The data type defaults
enum Temperatures:int
to int
{
WickedCold = 0,
FreezingPoint = 32,
LightJacketWeather = 60,
SwimmingWeather = 72, Why would you create
BoilingPoint = 212, enumerations?
}
20
22. Declaring Strings
A string is an object
string myString = “Hello World” ;// declare and initialise string
Where would you use strings
in your code?
22
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 ignored
myInt = myInt * 100;
23
24. Unit 2 Lab
To write statements that prompt and greet the user
1. Open Visual Studio.Net and create a new C# Console Application
project
2. 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.
24
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);
}
25
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
26
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
27
28. Calling Methods
Main
Statement1
Method A
Statement2 Call
Statement1
MethodA()
Statement2
Statement3
MethodB()
Statement4 Call
Statement3 Method B
End method
Statement4
Statement1
Return End method
Statement2
Statement3
Statement4
Return
End method
28
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!");
}
29
30. If Statements
Condition (always in brackets)
int valueOne = 10;
int valueTwo = 20;
if ( valueOne > valueTwo )
{
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}",
valueOne, valueTwo);
}
Statement
30
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
31
32. If … else Statements
Execute if condition
true
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
false
32
33. Nested if Statements
Outer if
if (temp <= 32) statement
{
Console.WriteLine("Warning! Ice on road!");
if (temp == 32) Nested if statement
Console.WriteLine( "Temp exactly freezing, beware of water.");
}
else
{
Console.WriteLine("Watch for black ice! Temp: {0}", temp);
}
Quiz: Are there a
missing braces?
33
34. Switch Statements
switch on the value of
myChoice
switch (myChoice)
{
case Democrat:
Console.WriteLine("You voted Democratic.");
break;
case Republican:
Console.WriteLine("You voted Republican.");
break;
case Progressive: Break out!
Console.WriteLine("You voted Progressive.");
break;
}
Execute case statements
depending on value
34
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?
35
36. Falling Through and Jumping Cases
case "NewLeft":
Console.WriteLine(
"The NewLeft members are voting Democratic.");
goto case "Democrat";
Jump Case
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
36
37. Looping Statements
Execute statements repeatedly
The number of time can depend on condition
Types of loop
Use goto statement
Use while loop
Use for loop
37
38. Creating Loops with goto
int counterVariable = -10; The label
repeat:
Console.WriteLine("counterVariable: {0}",counterVariable);
++counterVariable; Increment the
counter
if (counterVariable < 30) goto repeat;
Branch to label
Why is this type of loop
not a good idea?
38
39. The while Loop
While the condition is true …
while (counterVariable < 10)
{
Console.WriteLine("counterVariable: 0}",counterVariable);
counterVariable++;
}
… execute the
statements
39
40. The do … while Loop
do
{
Console.WriteLine("counterVariable:{0}",counterVariable);
counterVariable--;
} The condition is now
after the statements
while (counterVariable >0);
What is the minimum
number of times the
statements will run?
40
41. The for Loop
The counter variable changes on
each iteration
for (int counter=100; counter>80; counter--)
{
Console.WriteLine( "counter: {0} ", counter);
}
What numbers will be
output?
41
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
What is the next met, break out
statement executed
after a break out?
42
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?
43
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?)
44
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
45
46. 4. Operators
A symbol that takes an action
Assignment (=)
Mathematical ( +, -, *, / )
Increment and Decrement ( +=, -= )
Relational ( >, >=, <, <=)
Logical ( &&, ||, ! )
46
47. Assignment Operators (=)
Declare and assign
int smallInt = 5;
smallInt = otherInt= 5;
Multiple Assignments
47
48. Mathematical Operators
+ Add
- Subtract
* Multiply
/ Divide
% Modulus
What is the order of
precedence of
these operators?
48
49. The Modulus Operator (%)
for (int counter=1; counter<=100; counter++)
{
Console.Write("{0} ", counter);
If the remainder after
if ( counter % 10 == 0 ) dividing by 10 is 0
{
Console.WriteLine("t{0}", counter);
}
}
What will be
output?
49
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
50
51. Increment and Decrement by 1
++ intB; Increment
-- intB; Decrement
intA = ++ intB; Increment then assign - prefix
intA = -- intB; Decrement then assign - prefix
intA = intB ++; Assign then increment - postfix
intA = intB --; Assign then decrement - postfix
51
52. Prefix and Postfix Operators
Increment then
int original = 10; assign
int result;
result = ++original;
Console.WriteLine("After prefix: {0}, {1}", original,result);
result = original++;
Console.WriteLine("After postfix: {0}, {1}",original,result);
Assign then
increment
What numbers are
output?
52
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
53
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
54
55. The Conditional Operator (?)
Condition
int maxValue = valueOne > valueTwo ? valueOne : valueTwo;
Assign valueOne if true Assign valueTwo if false
55
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
57
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
58
59. What is OOP?
Windows and web programs are vastly complex
Richgraphical 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
59
60. Characteristics of Objects
State
The current conditions of an object, e.g. a customer
object‟s state may include address & phone number.
Capabilities
Whatthe 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.
60
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
61
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
62
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
63
64. Defining a Class
Class
public class Cat definition
{
private int weight; Fields
private String name;
public Cat(String name, int weight)
{
this.name = name;
this.weight = weight;
}
// Class code … A method
}
64
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 … Car
The automobile class is said to aggregate
the simpler classes Engine Wheels
Gear Box Piston
65
66. The Three Pillars of OOP
Good OO design is built on three sturdy pillars
Each 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
66
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)
67
68. Inheritance
Inheritance allows a new class to be Stringed
Instrument
derived from an existing class
The new (derived) class inherits
characteristics from the existing
(base) class Violin
The inheritance relationship is Violin is derived from a base
referred to as an is-a relationship class
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
68
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)
69
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
70
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
71
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);
}
} 72
73. Creating a Constructor
A constructor
Creates an instance of a class
Puts this in a valid state
The compiler will implicitly provide (if not declared)
Can provide with arguments
Can provide several overloaded versions of
constructor
Has same name as class & no return type
73
74. Creating a Constructor
public 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;
}
}
74
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
}
75
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 }
76
77. Instance and Static Members
Instance Members
Associated with instance of class
btnUpdate = new Button();
btnUpdate.Draw();
Static Members
Associated with class itself
Button.GetButtonCount();
77
78. Instance and Static Members
public 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);
}
78
}
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
call
protected override void Dispose( bool
disposing )
79
80. Encapsulating Data with Properties
Declare a property that
can be read from or
public int GetHour written to
get
{
return Hour;
}
set
{
Hour =value;
}
80
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
81
82. 7. Inside Methods
Several methods can have the same name
Overload method signature
Class data can be encapsulated with
properties
Provide clients controlled access to class state
Method can return multiple values by passing
parameters by reference
82
83. Overloading Method Signatures
Same method name
public Time(System.DateTime dt)
{ … } but a different number
& type of parameters
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)
{ … }
83
84. Passing Parameters by Reference
Declare a method that
takes parameters
passed by reference
public void GetTime(ref int h, ref int m, ref int s)
{
h = Hour;
m = Minute; Now call the method
s = Second; with reference
} parameters
t.GetTime(ref theHour, ref theMinute, ref theSecond);
84
85. Creating a Two Tier Application
Create the business tier
Create a new class library project
Create a class to represent a business entity, say Date
Add properties that expose attributes, say year, month, day
Add methods for business rules
Create the presentation tier
Create a new console application project
Add a reference to the above class library project
Create an object from class
Use the object‟s properties to access data items
Use the object‟s methods to perform business processes
85
86. Unit 7 Lab
To add a GetDate method to the Date class, using ref
parameters for year, month, day. Test the method.
86
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
87
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
89
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
90
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
91
94. Implementing Inheritance
Define Base Class
public class BaseForm : System.Windows.Forms.Form
Define Derived Class
public class AddressForm : BaseForm
Use Derived Class in Client Class
AddressForm af = new AddressForm();
af.Show();
94
95. Inside Inheritance
Calling the Base Class Constructor
public AddressForm():base()
Replacing Base Methods
protected new void OnCustomerLocate()
Calling Base Methods
base.OnCustomerLocate
95
96. Polymorphism
Powerful aspect of inheritance
Poly (many) – Morph (forms)
Example: T-Mobile supplies many handsets
Each handset “instance” knows how to ring
When the ring command is sent, the handset
obeys in its own way
96
97. Creating a Polymorphic Method
In Base
public class Window
public virtual void DrawWindow()
In Derived Class
public class ListBox : Window
public override void DrawWindow()
97
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();
}
98
99. Other Kinds of Methods
The derived class must implement a base
method
abstract public virtual void DrawWindow()
The derived class cannot override a base
method
sealed public virtual void DrawWindow()
99
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
100
101. 10. Operator Overloading
What is Operator Overloading
Using the Operator Keyword
Creating Useful Operators
The Equals Operator
Conversion Operators
101
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
102
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)
103
104. Defining an Operator
Create the
public Fraction(int numerator, int denominator) Fraction class
{
this.numerator=numerator;
this.denominator=denominator;
}
Create the +
public static Fraction operator+(Fraction lhs, Fraction rhs) operator
{
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
);
}
104
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
105
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
106
107. Overloading the Equals Method
Test if the
public override bool Equals(object o) parameter is an
{ object
if (! (o is Fraction) )
{
return false;
}
return this == (Fraction) o;
}
Use the
overloaded ==
to test for
equality
107
108. Overloading the == and != Operators
public static bool operator==(Fraction lhs, Fraction rhs)
{
if (lhs.denominator == rhs.denominator && Test for
lhs.numerator == rhs.numerator) equality of
{ Fractions
return true;
}
return false;
}
public static bool operator!=(Fraction lhs, Fraction rhs)
{
return !(lhs==rhs); Test for inequality by
} delegating to the ==
Why is it a good idea operator
to create both the ==
& != operators? 108
109. Using the == and != Operators
Test for equality
if (f4 == f3)
{
Console.WriteLine("f4: {0} == F3: {1}",
f4.ToString(),
f3.ToString());
}
if (f4 != f2) Test for inequality
{
Console.WriteLine("f4: {0} != F2: {1}",
f4.ToString(),
f2.ToString());
}
Where is the ToString()
method implemented?
109
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
110
111. Creating Conversion Operators
public Fraction(int wholeNumber) Constructor taking
{ a whole number
numerator = wholeNumber;
denominator = 1;
}
public static implicit operator Fraction(int theInt) Implicitly
{ converting int
return new Fraction(theInt); to fraction
}
public static explicit operator int(Fraction theFraction)
{
return theFraction.numerator /theFraction.denominator;
}
Explicitly
converting
Fraction to int 111
112. Using Conversion Operators
Fraction f1 = new Fraction(3,4);
Fraction f2 = new Fraction(2,4);
Fraction f3 = f1 + f2;
Fraction f4 = f3 + 5; Convert int to fraction implicitly
int truncated = (int) f4;
Convert fraction to int explicitly
112
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.
113
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
114
115. Defining a Struct
public struct Location
{ The struct has
private int xVal; private data
private int yVal;
public Location(int xCoordinate, int yCoordinate)
{
xVal = xCoordinate;
It has a
yVal = yCoordinate;
constructor
}
115
116. Defining a Struct 2
public int XVal
{
get { return xVal; }
set { xVal = value;} The struct has two
} properties …
public int YVal
{
get { return yVal; }
set { yVal = value; }
} … and a method
public override string ToString()
{
return (String.Format("{0}, {1}", xVal,yVal));
}
} // end struct
116
117. Using a Struct
Create an instance of the struct
Location loc1 = new Location(200,300);
Display the values in the struct
Console.WriteLine("Loc1 location: {0}", loc1);
Invoke the default constructor
Location loc2 = new Location();
Console.WriteLine("Loc2 location: {0}", loc2);
myFunc(loc1); Pass the struct to a method
What is output when
the default
constructor is used?
117
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.
118
119. 12. Interfaces
Implementing an Interface
Implementing More Than One Interface
Casting to an Interface
The is and as Operators
Extending Interfaces
Combining Interfaces
119
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
120
121. Implementing an Interface
Define the interface
interface IStorable
{
void Read();
void Write(object obj);
int Status { get; set; }
}
Define its properties
and methods
121
122. Create a Class to Implement the Interface
public class Document : IStorable
{
public void Read() Implement the Read
{ method
Console.WriteLine(
"Implementing the Read Method for IStorable");
}
public void Write(object o) Implement the Write
{ method
Console.WriteLine(
"Implementing the Write Method for IStorable");
}
public int Status Implement the
{ Status property
get{ return status; }
set{ status = value; }
}
122
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
123
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
124
125. Implementing Two Interfaces
interface IStorable
{
void Read();
void Write(object obj);
int Status { get; set; } Here's the
} new interface
interface ICompressible
{
void Compress();
void Decompress(); Document
}
implements both
interfaces
public class Document : IStorable, ICompressible
125
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
126
127. Casting to an Interface 2
public class Document : IStorable
The Document
class Implements
the IStorable
interface
Document doc = new Document("Test Document");
IStorable isDoc = (IStorable) doc;
isDoc.Read();
Cast the doc
What happens if the object to the
class does not IStorable type
implement the
interface? 127
128. The is Operator
Does the object
Document doc = new Document("Test Document"); implement
interface?
if (doc is IStorable)
{
IStorable isDoc = (IStorable) doc;
isDoc.Read();
}
else
Only cast if
{ does
Console.WriteLine("Could not cast to IStorable");
}
128
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
129
130. The as Operator 2
Document doc = new Document("Test Document");
IStorable isDoc = doc as IStorable;
if (isDoc != null)
{
Cast using as, then
isDoc.Read(); test for null
}
else
{
Console.WriteLine("Could not cast to IStorable");
}
130
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
131
132. Extending Interfaces 2
interface ICompressible Define ICompressible
{ interface
void Compress();
void Decompress();
}
interface ILoggedCompressible : ICompressible Extend ICompressible to
{ log the bytes saved
void LogSavedBytes();
}
Document implements
public class Document : ILoggedCompressible ILoggedCompressible
Now implement
public void LogSavedBytes()
{ that extra method
Console.WriteLine("Implementing LogSavedBytes");
}
132
133. Combining Interfaces
New interfaces can be created by adding
existing interfaces
New members can be added to the new
interface
133
134. Combining Interfaces 2
Add two existing interfaces
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize();
}
Add method
public class Document : IStorableCompressible
Class that will
implement the
interface
134
135. Unit 12 Lab
To 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.
135
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
136
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
… 137
138. Declaring Arrays
Declare arrays
int[] intArray;
Employee[] empArray;
intArray = new int[5];
empArray = new Employee[3];
What are the default
values of the array Initialise arrays with 5
elements? & 3 elements
138
139. Declaring Arrays 2
Declare and
initialise arrays
int[] intArray = new int[5];
Employee[] empArray = new Employee[3];
The default values for Alternatively, declare,
integers are 0, and for objects
initialise and
null
populate arrays
int[] intArray = { 2, 4, 6, 8, 10 };
Employee[] empArray =
{ new Employee(5), new Employee(7), new Employee(9) };
139
140. Accessing Array Elements
This returns the 4th element since
indexing starts at 0
intArray[3];
Populate the Employee array
using a loop
for (int i = 0;i<empArray.Length;i++)
{
empArray[i] = new Employee(i+5);
Console.WriteLine(empArray[i].empID);
}
140
141. The foreach Statement
Loop through all items in the
array
foreach( int theInt in intArray )
{
Console.WriteLine(theInt.ToString());
}
141
142. The params keyword
The method takes a variable
number of integers
as a parameter
public void DisplayVals(params int[] intVals)
{
foreach (int i in intVals)
{
Console.WriteLine("DisplayVals {0}",i);
}
}
int [] explicitArray = new int[4] {5,6,7,8};
DisplayVals(explicitArray);
Call method passing
an array
142
144. Declaring 2D Arrays
Declare the array
int[,] boxArray = new int[2,3];
int[,] rectangularArray =
{
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11}
};
Or declare and populate
the array
144
145. Loop through 2D Array
Outer loop
for (int i = 0;i < rows;i++)
{
for (int j = 0;j<columns;j++) Inner loop
{
Console.WriteLine("rectangularArray[{0},{1}] = {2}",
i,j,rectangularArray[i,j]);
}
}
Which is iterated through
first, the rows or the
columns?
145
146. Jagged Arrays (Array of Arrays)
int[][] jaggedArray = new int[rows][]; Declare the rows of
various lengths
jaggedArray[0] = new int[3];
jaggedArray[1] = new int[7];
jaggedArray[2] = new int[9];
Fill some elements
jaggedArray[0][3] = 15;
jaggedArray[1][1] = 12;
jaggedArray[2][1] = 9;
146
147. System.Array Class
Arrays are implemented
with the System.Array class,
which provides these useful
methods:
Clear()
Copy()
Reverse()
Sort()
Length()
Rank()
147
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];
148
149. Indexing Classes
public class ListBoxTest
{ Allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// handle bad index
Get value from
}
internal array
return strings[index];
}
set
{ Set value in
strings[index] = value; internal array
}
} 149
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]);
}
150
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
151
152. 14. Collection Interfaces and Types
The Collection Interfaces
Array Lists
Queues
Stacks
152
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
153
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
154
155. The Collection Interfaces 2
Interface 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 155
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
156
157. Array List Members
Method or Purpose
Property
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
157
158. Array List Example
ArrayList empArray = new ArrayList();
ArrayList intArray = new ArrayList();
Populate the
for (int i = 0;i<5;i++) ArrayLists
{
empArray.Add(new Employee(i+100));
intArray.Add(i*5);
}
foreach (int i in intArray)
{
Console.Write("{0} ", i.ToString()); Print the
}
ArrayLists‟
foreach(Employee e in empArray) members
{
Console.Write("{0} ", e.ToString());
}
158
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
159
160. Queues Members
Method or Purpose
Property
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
160
161. A Queue Example
Populate the
Queue intQueue = new Queue(); Queue
for (int i = 0;i<5;i++)
{
intQueue.Enqueue(i*5);
}
Console.Write("intQueue values:t" ); Remove
DisplayValues( intQueue ); elements
Console.WriteLine("n(Dequeue)t{0}", intQueue.Dequeue() );
DisplayValues( intQueue );
Console.WriteLine("n(Dequeue)t{0}", intQueue.Dequeue() );
DisplayValues( intQueue );
View but
Console.WriteLine("n(Peek) t{0}", intQueue.Peek() ); do not
DisplayValues( intQueue ); remove
elements
161
162. Displaying Queue Values
The parameter type
is IEnumerable
public static void DisplayValues( IEnumerable myCollection )
{
IEnumerator myEnumerator = myCollection.GetEnumerator();
while ( myEnumerator.MoveNext() )
Console.Write( "{0} ",myEnumerator.Current );
Console.WriteLine();
}
Iterate thought items
of the collection
How does the IEnumerable
interface work?
162
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()
163
164. Stack Members
Method or Purpose
Property
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
164
165. A Stack Example
Declare &
populate the
Stack intStack = new Stack(); stack
for (int i = 0;i<8;i++)
{
intStack.Push(i*5); Remove an
} element
Console.WriteLine( "n(Pop)t{0}", intStack.Pop() ); View an
element
Console.WriteLine( "n(Peek) t{0}",intStack.Peek() );
DisplayValues( intStack );
Display all
elements
165
166. Displaying Stack Values
The parameter is
of type
public static void DisplayValues( IEnumerable
IEnumerable myCollection )
{
foreach (object o in myCollection)
{
Console.WriteLine(o);
}
}
Iterate thought items
of the collection
166
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.
167
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:
Concatenation
Comparison
Extracting sub-stings
169
170. Creating Strings
Declare a
string s1 = "abcd"; string
Declare a string with an
string s2 = "ABCDn"; escape character for a
new line
string s3 = "ABCDt EFGH"; Use an escape
character for a tab
string s4 = myInteger.ToString();
Use the ToString() method 170
171. Comparing Strings
string s1 = "abcd"; Hold the results of comparisons
string s2 = "ABCD";
int result;
Compare two strings, case sensitive
result = string.Compare(s1, s2);
Console.WriteLine("compare s1: {0}, s2: {1}, result: {2}n",
s1, s2, result);
Compare, case insensitive
result = string.Compare(s1,s2, true);
Console.WriteLine("Compare insensitive. result: {0}n",
result);
If result is negative, the first value is smaller
If result is positive, the first value is bigger
If result is zero, the values are equal
171
173. Copying Strings
Copy method
string s5 = string.Copy(s2);
string s6 = s5;
Use the overloaded =
operator
173
174. Test for Equality
Use the member
if s6.Equals(s5)…; method
if string.Equals(s6,s5)…; Use the static
method
if s6 == s5 …;
Use the
overloaded ==
operator
174
175. Other Useful Methods
Method Return value or action
s3.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
175
176. Splitting Strings 1
string s1 = "One.Two;Three Four";
A string to split
const char Space = ' ';
const char Comma = ',';
const char Stop = '.'; The string
const char SemiColon = ';';
delimiters
char[] delimiters = new char[]
{
Space,
Comma,
Stop, Put the
SemiColon delimiters
};
string output = "";
in an array
int ctr = 1;
176
177. Splitting Strings 2
Split the string
String[] resultArray = s1.Split(delimiters);
foreach (String subString in resultArray)
{
output += ctr++;
output += ": ";
output += subString;
output += "n";
} Iterate over the
Console.WriteLine(output); resulting array of strings
177
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
178
179. The StringBuilder Class 2
Use the
StringBuilder
class to build the
StringBuilder output = new StringBuilder(); output
int ctr = 1;
Split the string
foreach (string subString in s1.Split(delimiters))
{
output.AppendFormat("{0}: {1}n",ctr++,subString);
}
Console.WriteLine(output);
AppendFormat appends a
formatted string
179
180. StringBuilder Methods
Method Explanation
Append() Append string at end of current string
AppendFormat() Append formatted string at end of current string
AppendFormat appends a formatted 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
180
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
return
A substring
A modification of the original
181
182. Regular Expressions 2 Define the
Regular
Expression
string s1 = "One,Two,Three Liberty Associates, Inc.";
Regex theRegex = new Regex(" |, |,");
StringBuilder sBuilder = new StringBuilder(); Spit the string
int id = 1; using the Regular
Expression
foreach (string subString in theRegex.Split(s1))
{
sBuilder.AppendFormat({0}: {1}n", id++, subString);
}
Console.WriteLine("{0}", sBuilder);
182
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.
183
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
184
185. Exception Handling
C# handles errors and abnormal conditions
with exceptions
Exceptions can be thrown by
A throw statement
A .Net Framework class
The operating system (e.g. a security violation)
Exceptions are caught by code in a catch
block (i.e. an exception handler)
185
186. The Exception Class
All exceptions are of type System.Exception or
derived from this
Exceptions types include
ArgumentNullException
InvalidCastException
OverflowException
Exception objects provide information on what
went wrong (message, help file, source …)
186
187. Try and Catch Statements
public void Func1()
{
Test for
Console.WriteLine("Enter Func1...");
try errors in try
{ block
Console.WriteLine("Entering try block...");
Func2(); Run
Console.WriteLine("Exiting try block..."); statement in
} catch block if
catch an error
{ occurs
Console.WriteLine("Exception caught and handled!");
}
Console.WriteLine("Exit Func1...");
}
187
188. Searching for an Exception Handler
Main
Unwind the call
Statement1 stack looking
Method A
Statement2 Call for a handler
Statement1
MethodA()
Statement2
Statement3
MethodB() Call
Statement4
Statement3
End method Method B
Statement4 Statement1
Search for
handler End method Statement2 Exception
thrown !!
Statement3
Search for
If no exception handler, then handler Statement4
the CLR handles the exception End method
188
189. The throw Statement
public void Run() The exception
{ is unhandled
Console.WriteLine("Enter Run..."); so the program
Func1(); terminates
Console.WriteLine("Exit Run...");
}
public void Func1()
{
Console.WriteLine("Enter Func1...");
Func2();
Console.WriteLine("Exit Func1...");
}
public void Func2()
{ Throw an
Console.WriteLine("Enter Func2..."); exception
throw new System.Exception();
Console.WriteLine("Exit Func2...");
}
189
190. How the Call Stack Works
public void Run()
{
Func1();
}
public void Func1()
catch in
{ Func1
try
{
Func2();
}
catch
{
Console.WriteLine("Exception caught and handled!");
}
}
public void Func2() throw in
{ Func2
Console.WriteLine("Enter Func2...");
throw new System.Exception(); Will this
Console.WriteLine("Exit Func2..."); statement run?
}
190
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
191
192. Creating Dedicated catch Statements 2
try
{
double a = 5;
double b = 0;
DoDivide(a,b) The most derived exception type is first
}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException caught!");
}
catch (System.ArithmeticException)
{
Console.WriteLine("ArithmeticException caught!");
}
catch
{
Console.WriteLine("Unknown exception caught");
}
Why are the catch
statements in this
The generic exception type is last order ? 192
193. The finally Statement
try
{
double a = 5;
double b = 0;
DoDivide(a,b)
}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException caught!");
}
catch
{
Console.WriteLine("Unknown exception caught");
}
finally This statement
{ must execute
Console.WriteLine(“close files here");
}
What is another way of making
this statement always run ? 193
194. Exception Class Methods and Properties
Member Explanation
Source 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
194
195. Using the Exception Class
DivideByZeroException e = new DivideByZeroException();
e.HelpLink ="http://www.la.com";
throw e;
Set exception
property
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);
}
Display exception
properties
195
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.
196
197. 17. Delegates and Events
So what are
Robin Cook has died delegates?
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
197
198. Delegates in C#
A delegate
encapsulates a method
has a specific return type & parameter list
is instantiated with by passing a method as parameter
can call the delegated method at runtime
198
199. Using Delegates
Define the delegate
Public delegate int WhichIsFirst(object obj1, object obj2);
Instantiate the delegate with a method
WhichIsFirst theStudentDelegate = new
WhichIsFirst(WhichStudentComesFirst);
Call the delegated method
i= theStudentDelegate(objJohn, objFred);
199
200. Multicasting Delegates
Create a single delegate
that calls multiple methods
Combine delegates with the + or += operators
myMulticastDelegate = Writer + Logger;
200
201. Multicasting Delegates
// Define delegate
public delegate void StringDelegate(string s);
// Define two methods
public static void WriteString(string s) { …}
public static void LogString(string s) {…}
// Define and instantiate two StringDelegate objects.
StringDelegate Writer, Logger
Writer = new StringDelegate(WriteString);
Logger = new StringDelegate(LogString);
//Multicast the delegate
myMulticastDelegate = Writer + Logger;
//Call the two delegated methods
myMulticastDelegate(“log this string")
201
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
202
204. Coupling Delegates to Event Handlers
Delegates Event Handlers
linkLabel1.MouseEnter += new EventHandler(Bigger);
linkLabel2.MouseEnter += new EventHandler(Bigger);
linkLabel3.MouseEnter += new EventHandler(Bigger);
204
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.
205
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
206
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>();
207
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);
208
209. The Benefits of Generics
Import the Generic
.Net class
Declare a list
using System.Collections.Generic; using the type
parameter
List<int> list1 = new List<int>();
Add element
list1.Add(3);
without casting
or boxing
list1.Add("It is raining in the South West");
Generate compile-
time error!
209
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
210
211. Parameter Constraints
Constraint Explanation
class MyList<T> where The type argument must be a value type
T: struct
class MyList<T> where The type argument must be a reference
T: class type
class MyList<T> where The type argument must have a public
T: new() parameterless constructor
class MyList<T> where The type argument must be or derive from
T: <base class name> the specified base class
class MyList<T> where The type argument must be or implement
T: <interface name> the specified interface
211
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>
212
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
213
214. Creating Generic Methods
void Swap<T>( ref T lhs, ref T rhs) A generic
{ method with a
type parameter
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
} Calling the method
using the type
parameter
int a = 1;
int b = 2;
Swap<int>(ref a, ref b);
Or, calling the method
inferring the type
Swap(ref a, ref b); parameter
214
217. New Language Features in C# 3.0
•Implicit Typing
•Anonymous Types
•Object and Collection Initialisers
•Extension Methods
•Partial Methods
•Lambda Expressions
218. 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());
219. 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);