Kurt Nørmark ©
Department of Computer Science, Aalborg University, Denmark
Abstract Previous lecture Next lecture Index References Contents | Delegates is a new kind of types that hold operations (methods). Events are variable of delegate types. Therefore we have found it natural to also to cover delegates and events in this lecture. At the end of the lecture we study the observer design pattern, because this pattern is natural to deal with in terms of delegates and events. |
Overloaded Operators |
Why operator overloading? Slide Annotated slide Contents Index References Textbook | Operator overloading is about use of ordinary operatorsl like + and !=, for non-simple types. On this page will motivate you for operator overloading. |
|
Program: Comparison of operator notation and function notation. Illustrates that use of operator notation is much briefer than use of method notation - at
least when we use natural names of the operations. |
|
Program: The class MyInt. How the methods used above can be be implemented as static methods in the MyInt class. |
|
Read more about motivation for operator overloading in the text book version of this material. |
Overloadable operators in C# Slide Annotated slide Contents Index References Textbook | Overview of overloadable operators. |
|
Table. The operator priority table of C#. The operators that can be overloaded directly are emphasized. |
|
Read more about overloadable C# operators in the text book version of this material. |
An example of overloaded operators: Interval Slide Annotated slide Contents Index References Textbook | We introduce a new type, struct Interval, in which we implement a number of operations by overloads of some of the well-known C# operators. |
|
Program: The struct Interval. This type defines a number of overloaded operators in struct Interval. |
|
Program: A client program of struct Interval. This class uses the operators on given interval values. |
|
Program: Output from the interval application. |
|
Exercise 6.3. Interval indexer | The Interval type represents an oriented interval [from - to] of integers. We use the Interval example to illustrate the overloading of operators. If you have not already done so, read about the idea behind the struct Interval in the course teaching material. In the client of struct Interval we use an indexer to access elements of the interval. For some interval i, the expression i[0] should access the from-value of i, and i[i.Length-1] should access the to-value of i. Where, precisely, is the indexer used in the given client class? Add the indexer to the struct Interval (getter only) which accesses element number j (0 <= j <= i.Length) of an interval i. Hint: Be careful to take the orientation of the interval into account. Does it make sense to program a setter of this indexer? |
Exercise 6.3. An interval overlap operation | In this exercise we continue our work on struct Interval, which we have used to illustrate overloaded operators in C#. Add an Interal operation that finds the overlap between two intervals. Your starting point should be the struct Interval. In the version of struct Interval, provided as starting point for this exercise, intervals may be empty. Please analyze the possible overlappings between two intervals. There are several cases that need consideration. The fact that Interval is oriented may turn out to be a complicating factor in the solution. Feel free to ignore the orientation of intervals in your solution to this exercise. Which kind of operation will you chose for the overlapping operation in C# (method, property, indexer, operator)? Before you program the operation in C# you should design the signature of the operation. Program the operation in C#, and test your solution in an Interval client program. You may chose to revise the Interval client program from the teaching material. |
Program: The class PlayingCard with relational operators. The operators ==, !=, <, and > in class Card. |
|
Read more about the interval and playing card examples in the text book version of this material. |
Some details of operator overloading Slide Annotated slide Contents Index References Textbook | Additional details about operator overloading. Not the full story, however. |
Syntax: The C# syntax for definition of an overloaded operator. |
|
|
|
Delegates |
Delegates in C# Slide Annotated slide Contents Index References Textbook | Delegates are types. The objects in such types are methods. With the introduction of delegates, methods become data. |
|
Program: A Delegate of simple numeric functions. An example which defines a simple delegate (a type of methods) called NumericFunction.
The example illustrates both existing, named methods in NumericFunction and
a new, anonymous method in in the type. |
|
Program: Output from the NumericFunction delegate program. |
|
Program: The static method Compose in class Application. Illustrates a method that takes two NumericFunction objects as input, and which returns
a NumericFunction. |
|
Program: Output from the Compose delegate program. |
|
|
Exercise 6.5. Finding and sorting elements in an array | In this exercise we will work with searching and sorting in arrays. To be concrete, we work on an array of type Point, where Point is the type we have been programming in earlier exercises. Via this exercise you are supposed to learn how to pass a delegate to a method such as Find and Sort. The purpose of passing a delegate to Find is to specify which point we are looking for. Make an array of Point objects. You can, for instance, use this version of class Point. You can also use a version that you wrote as solution to one of the previous exercises. Use the static method System.Array.Find to locate the first point in the array that satisfies the condition: The sum of the x and y coordinates is (very close to) zero The solution involves the programming of an appropriate delegate in C#. The delegate must be a Point predicate: a method that takes a Point as parameter and returns a boolean value. Next, in this exercise, sort the list of points by use of one of the static Sort methods in System.Array. Take a look at the Sort methods in System.Array. There is an overwhelming amount of these! We will use the one that takes a Comparison delegate, Comparison<T>, as the second parameter. Please find this method in your documentation browser. Why do we need to pass a Comparison predicate to the Sort method? Comparison<Point> is a delegate that compares two points, say p1 and p2. Pass an actual delegate parameter to Sort in which p1 <= p2 if and only if p1.X + p1.Y <= p2.X + p2.Y Please notice that a comparsion between p1 and p2 must return an integer. A negative integer means that p1 is less than p2. Zero means that p1 is equal to p2. A positive integer means that p1 is greater than p2. Test run you program. Is your Point array sorted in the way you excepts? |
Exercise 6.5. How local are local variables and formal parameters? | When we run the following program
we get this output
Explain! |
Read more about delegates in the text book version of this material. |
Delegates that contain instance methods Slide Annotated slide Contents Index References Textbook | The methods on the previous page were all static. We will now explain how to deal with instance methods in relation to delegates. |
|
Program: A Messenger class and a Message delegate. Class Messenger encapsulates a Message delegate. Via the DoSend method it is possible
to activate the method(s) in the encapsulated Message delegate. |
|
Program: A very simple class A with an instance method MethodA. A class A with an instance method MethodA. |
|
Program: An Application class which accesses an instance method in class A. Illustrates how to deal with an instance method of a particular object as a delegate. |
|
Program: Output from Main of class Application. Confirms that MethodA in a2 is called. |
|
Read more about delegates with instance methods in the text book version of this material. |
Multivalued delegates Slide Annotated slide Contents Index References Textbook | A delegate can contain more than one method. |
|
Program: Install and UnInstall message methods in the Messenger class. Similar to class Messenger on the previous page. Allows adding and subtraction of methods to the delegate
in a Messenger object
via the methods InstallMessage and UninstallMessage. |
|
Program: A simple class A. Identical to class A on the previous page. Just a simple class with an instance method. |
|
Program: An Application class. Illustrates that it is possible to add (and delete) a number of different methods (of same signature)
to a given instance of class Messenger. |
|
Program: Output from Main of class Application. Confirms that a delegate calls all of its methods. |
|
|
Read more about multivalued delegates in the text book version of this material. |
Lambda Expressions Slide Annotated slide Contents Index References Textbook |
|
Program: Five equivalent functions - from anonymous method expressions to lambda expressions. |
|
Program: Program output. |
|
|
Events |
Events Slide Annotated slide Contents Index References Textbook |
The concept event: In a program, an event contains some actions that must be carried out when the event is triggered |
|
|
Events in C# Slide Annotated slide Contents Index References Textbook |
|
|
|
Examples of events Slide Annotated slide Contents Index References Textbook |
|
Program: The die class with history and dieNotifier. |
|
Program: A client of die that reports 'two sixes in a row' via an event. |
|
Program: Possible program output of the die application (abbreviated). |
|
Exercise 6.6. Additional Die events | In this exercise we add yet another method to the existing event i class Die, and we add another event to Die. In the Die event example, we have a public event called twoSixesInARow which is triggered if a die shows two sixes in a row. In the sample client program we add an anonymous method to this event which reports the string parameter of the event on standard output. Add yet another method to the twoSixesInARow event which counts the number of times 'two sixes in a row' appear. For this purpose we need - quite naturally - an integer variable for counting. Where should this variable be located relative to the 'counting method': Will you place the variable inside the new method, inside the Die class, or inside the client class of the Die? Add a similar event called fullHouse, of the same type Notifier, which is triggered if the Die tosses a full house. A full house means (inspired from the rules of Yahtzee) two tosses of one kind and three tosses of another kind - in a row. For instance, the toss sequence 5 6 5 6 5 leads to a full house. Similarly, the 1 4 4 4 1 leads to a full house. The toss sequence 5 1 6 6 6 6 5 does not contain a full house sequence, and the toss sequence 6 6 6 6 6 is not a full house. Be sure to test-drive the program and watch for triggering of both events. |
Program: A window with two buttons and a textbox. |
|
Patterns and Techniques |
Motivation - Example Slide Annotated slide Contents Index References |
The subject (weather service object) to the left and its three observers (weather watcher objects) to the right. The Weather Service Object get its information various sensors. |
The observer design pattern Slide Annotated slide Contents Index References Textbook |
The subject (weather service object) to the left and its three observers (weather watcher objects) to the right. The Weather Service Object get its information various sensors. |
The loose couple is ensured by observers that subscribe to events from the subjects.
Upon interesting and relevant events in the subject, the subject broadcasts to its observers.
The observers may then ask the subject to supply additional information. The main resposibility is shifted from the subject to the observers. |
|
Program: Template of the Subject class. The subject class corresponds to the Weather Service. |
|
Program: A templates of the Observer class. The observer class corresponds to a Weather Watcher. |
|
Program: Application of the Subject and Observer classes. A client class that sets up the subject and the observers, handles subscriptions,
and notifies the subject. |
|
An Observer Example Slide Annotated slide Contents Index References |
|
Program: A WeatherCenter (subject) and TemperatureWatcher (observer). |
|
Program: Application of the WeatherCenter and TemperatureWatcher. |
|
Program: Output of the WeatherCenter and TemperatureWatcher application. |
|
|
|
Observer with Delegates and Events Slide Annotated slide Contents Index References Textbook |
|
Program: Template of the Subject class. |
|
Program: Template of the Observer class. |
|
Program: Application of the Subject and Observer classes. |
|
Observer Example with Delegates and Events Slide Annotated slide Contents Index References |
Program: Application of the two different Watchers. |
|
Program: A WeatherCenter (subject) and Temperature/Rain Watchers (observer) with events. |
|
Program: Output of the WeatherCenter and Watchers application. |
|
Collected references Contents Index |
|
Chapter 6: Operators, Delegates, and Events
Course home Author home About producing this web Previous lecture (top) Next lecture (top) Previous lecture (bund) Next lecture (bund)
Generated: February 7, 2011, 12:15:45