Prof . Yousef B. Mahdy, Assuit Software Development

Software Development
and Professional
Practice
Event-driven
programming
Prof. Yousef B. Mahdy
Prof. Yousef B. Mahdy -2017, Assuit University, Egypt
Introduction





2-
At one point in our careers we've all been introduced to,
or at least heard of, event driven programming,
programming where the overall flow of the application
is controlled by user generated events.
In C# event driven programming is made much easier
with the offering of Delegates & Events.
So today we're going to look at event driven
programming in C#. Before we get into the meat of
event driven programming we need to set a couple
definitions for terms we will be using in this part:
Delegate:
A delegate is very similar to a function pointer in C++.
It is a reference type that encapsulates a method which
has a specific signature and a return type.
Prof . Yousef B. Mahdy, Assuit
Software Development
1





3-
Events:
An event allows an object to send notifications to other
classes (or objects) that something has occurred. In
simple terms an event is the outcome of a specific action.
In the old days all programs were very linear, they
followed a set of commands/paths and user interaction
was merely an after-thought, or limited to filling in forms
or providing data.
Over time things have changed drastically, today
programs are more user driven than ever, and as
developers we need to change & adapt to this.
In today environment we as developers know that actions
are going to need to be taken, but at design-time we do
not know what order these actions are going to occur,
because it's all dependent on what actions the users take.
Prof . Yousef B. Mahdy, Assuit
Software Development
2



4-
We know we're going to have to execute an action, but
until the user makes their action we dont know which
method (or event) is supposed to be executed. That's
where event driven programming comes into play. With
events & delegates we can make these decisions on the
fly.
So how exactly do delegates & events help with event
driven programming you may ask? Well I have an
answer.
In event driven programmer you have a publisher, (a
class that exposes the event) and at least one
subscriber, a class that subscribes to your event
through the use of a delegate.
Prof . Yousef B. Mahdy, Assuit
Software Development
3

5-
So, given that context your publisher raises an event,
more than likely through some user interaction or user
choice, and your subscriber makes a decision on what
to execute based on what event was raised, thus the
term event driven programming.
Prof . Yousef B. Mahdy, Assuit
Software Development
Delegates






6-
A delegate in C# is similar to a function pointer in C or
C++.
Using a delegate allows the programmer to encapsulate
a reference to a method inside a delegate object.
The delegate object can then be passed to code which
can call the referenced method, without having to know
at compile time which method will be invoked.
Delegates are often used to implement callbacks and
event listeners. A delegate does not need to know
anything about classes of methods it works with.
A delegate is a reference type. But instead of referring
to an object, a delegate refers to a method. Delegates
are used in the following cases:
Event handlers– Callbacks –LINQ --Implementation of
design patterns
Prof . Yousef B. Mahdy, Assuit
Software Development
1

There is nothing that is done with delegates that cannot
be done with regular methods. Delegates are used
because they bring several advantages.
» They foster flexibility of the application and code reuse.
Like interfaces, delegates let us decouple and generalize
our code.
» Delegates also allow methods to be passed as parameters.
» When we need to decide which method to call at runtime,
we use a delegate.
» Finally, delegates provide a way of specializing behavior of
a class without subclassing it. Classes may have complex
generic behavior but are still meant to be specialized.
Classes are specialized either through inheritance or via
delegates.
7-
Prof . Yousef B. Mahdy, Assuit
Software Development
Call a Function directly - No Delegate
8-
Prof . Yousef B. Mahdy, Assuit
Software Development
2

That works well in most situations. Sometimes,
however, we don't want to call a function directly - we'd
like to be able to pass it to somebody else so that they
can call it.
This is especially useful in an event-driven system such
as a graphical user interface, when I want some code to
be executed when the user clicks on a button, or when
I want to log some information but can't specify how it
is logged.
9-
Prof . Yousef B. Mahdy, Assuit

Software Development
The very basic Delegate




An interesting and useful property of a delegate is that
it does not know or care about the class of the object
that it references.
Any object will do; all that matters is that the method's
argument types and return type match the delegate's.
This makes delegates perfectly suited for "anonymous"
invocation.
The signature of a single cast delegate is shown below:
delegate result-type identifier ([parameters]);
where:
» result-type: The result type, which matches the return
type of the function.
» identifier: The delegate name.
» parameters: The Parameters, that the function takes.
10 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Examples:

A delegate will allow us to specify what the function
we'll be calling looks like without having to specify
which function to call. The declaration for a delegate
looks just like the declaration for a function, except that
in this case, we're declaring the signature of functions
that this delegate can reference.
11 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1





There are three steps in defining and using delegates:
Declaration
Instantiation
Invocation
A very basic example:
12 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
13 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Calling Static Functions

For
our
next,
more
advanced
example
(SimpleDelegate2.cs), declares a delegate that takes a
single string parameter and has no return type:
14 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
15 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Calling Member Functions
16 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
17 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Combining delegates (Multicasting)



Being able to point to member functions is nice, but
there are more tricks you can do with delegates. In C#,
delegates are multicast, which means that they can
point to more than one function at a time (that is,
they're based off the System.MulticastDelegate type). A
multicast delegate maintains a list of functions that will
all be called when the delegate is invoked.
Combining two delegate instances is usually done using
the addition (+) operator, as if the delegate instances
were strings or numbers. Subtracting one from another
is usually done with the subtraction (-) operator.
Note that when you subtract one combined delegate
from another, the subtraction works in terms of lists. If
the list to subtract is not found in the original list, the
result is just the original list.
18 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1

Otherwise, the last occurrence of the list is removed.
This is best shown with some examples. Instead of
actual code, the following uses lists of simple
delegates d1, d2 etc. For instance, [d1, d2, d3] is a
combined delegate which, when executed, would
call d1 then d2 then d3. An empty list is represented
by null rather than an actual delegate instance.
19 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
20 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3
21 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4
22 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Anonymous methods



Anonymous methods provide a technique to pass a
code block as a delegate parameter. Anonymous
methods are the methods without a name, just the
body.
You need not specify the return type in an anonymous
method; it is inferred from the return statement inside
the method body.
Anonymous methods are declared with the creation of
the delegate instance, with a delegate keyword. For
example,
delegate void NumberChanger(int n);
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
23 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
24 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
25 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Delegates as method parameters

Delegates can be used as method parameters.
26 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Invocation List



Multicast delegates provide functionality to execute
more than one method. Internally, a linked list of
delegates (called Invocation List) is stored, and when
the multicast delegate is invoked, the list of delegates
will be executed in sequence.
If a delegate instance has an invocation list with
multiple methods and you invoke the delegate using
the standard functional notation, you’ll get back the
return value only for the last method in the invocation
list.
If you want to consume the return value for each
method in a delegate’s invocation list, you can
use GetInvocationList to explicitly iterate through the
invocation list.
27 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Lambda Expressions




Lambda expressions are similar to anonymous methods
introduced in C# 2.0, except that lambda expressions
are more concise and more flexible.
All lambda expressions use the lambda operator =>,
which is read as "goes to". The left side of the lambda
operator specifies the input parameters and the right
side holds the expression or statement block.
Lets take an example:
delegate int Del (int i);
With C# 2.0, anonymous methods allow you to write a
method and initialize a delegate in place:
28 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
Del myDelegate = new Del(
delegate(int x){
return x * 2;
});
Console.WriteLine("{0}", myDelegate(5));



29 -
The segment inside the braces of Del is also called as
Anonymous Function.
Now lets convert it to a Lambda Expression:
Del myDelegate = x => x * 2;
x => x * 2 is the expression that is the known as
Lambda Expression. All lambda expressions use the
lambda operator =>, which is read as "goes to".
Prof . Yousef B. Mahdy, Assuit
Software Development
2
The left side of the lambda operator specifies the input
parameters (if any) and the right side hold the
expression or statement block. The lambda expression
x => x * 2 is read "x goes to 2 times x." This reduced
the no. of lines as you can see and the output is still
the same.
 The above expression can be generalized for clearer
understanding.
(input parameters) => Expression;
 and can be called as "Expression Lambdas" since
single Expression is involved here.
 It can contain multiple statements and can be
surrounded by { } just like anonymous functions.
(input param1, input param2) => { statement1,
Statement 2};

30 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3
delegate int Del2(int a, int b);
Del2 getBigInteger = (x, y) => { if (x > y)
return x; else return y; };
Console.WriteLine(getBigInteger(10,15));
 You can raise a question here, how x & y are being
treated as integer while you didn't declared them as
integer?
 Here is the answer. When writing lambdas, you often
do not have to specify a type for the input parameters
because the compiler can infer the type based on the
lambda body, the underlying delegate type, and other
factors as described in the C# Language Specification.
 Anonymous function that take no parameter and
return nothing can be written in form of a Lambda
Expression like below:
31 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4
delegate void doSomething();
doSomething
IamVoid
=
()
=>
{
Console.WriteLine("Hello there! I take nothing and
return nothing"); };
//call the Anonymous function
IamVoid();
 Example:
 LINQ to Objects
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
32 -
Prof . Yousef B. Mahdy, Assuit
Software Development
What is Func?





33 -
Func in short is parameterized delegate.
In C#, a delegate instance points towards a method.
When a caller invokes the delegate, it calls its target
method. This way, the caller is not invoking the target
method rather invoking the delegate which can call the
target method.
We do it because it creates an abstraction on invoking
the target method.
We of course always can invoke a method directly but
decoupling of the client and target method is
sometimes a need or gives us more flexibility to make
things clean and simple.
We can use Func delegate to represent a method that
can be passed as a parameter without explicitly
declaring a custom delegate.
Prof . Yousef B. Mahdy, Assuit
Software Development
Programming Action delegates in C#



34 -
The basic difference between Func and Action
delegates is that while the former is used for delegates
that return value, the latter can be used for those
delegates in which you don't have any return value.
Func is a delegate that points to a method that
accepts one or more arguments and returns a value.
Action is a delegate that points to a method which in
turn accepts one or more arguments but returns no
value. In other words, you should use Action when
your delegate points to a method that returns void.
Prof . Yousef B. Mahdy, Assuit
Software Development
Example
35 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Example




36 -
Write a C# program to sort a list of objects using
bubble sort algorithm (generic bubble sort) based on
delegate?
Solution:
Bubble
sort
is
one
of
the
most
inefficient sorting algorithms. At each step, if two
adjacent elements of a list are not in order, they will
be swapped. Thus, smaller elements will "bubble" to
the front, (or bigger elements will be "bubbled" to the
back, depending on implementation) and hence the
name. Its time complexity O(n2).
This algorithm is almost never recommended,
as insertion sort has the same asymptotic complexity,
but only requires swaps. Bubble sort is stable, as two
equal elements will never be swapped.
Prof . Yousef B. Mahdy, Assuit
Software Development
1
37 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
38 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3
39 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4
40 -
Prof . Yousef B. Mahdy, Assuit
Software Development
41 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Events



Events are user actions such as key press, clicks, mouse
movements, etc., or some occurrence such as system
generated notifications. Applications need to respond to
events when they occur. For example, interrupts. Events
are used for inter-process communication.
Events are nothing just a user action. For example
» When you click with mouse – It is mouse click events.
» When you press any key in keyboard – It is Key Press
events
» When you refresh your webpage – It is page load events
» When you move mouse cursor – It is mouse hover events
etc.
So when you take any action like key press, mouse
movements, clicks etc an event raised. Let me clear
more about it. For example, you filled an online form
and click on submit button.
42 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
» In the background button_click() event raised(fired).
» This event calls and execute an associated function (event
handler).
» This function processes your request and submits page
information to database.



The basic foundation behind this programming model is
the idea of "publisher and subscribers."
In this model, you have publishers who will do some
logic and publish an "event." Publishers will then send
out their event only to subscribers who have
subscribed to receive the specific event.
In C#, any object can publish a set of events to which
other applications can subscribe. When the publishing
class raises an event, all the subscribed applications are
notified.
43 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
44 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3
45 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4



publisher: where the events happen. Publisher should
specify which delegate the class is using and generate
necessary arguments, pass those arguments and itself
to the delegate.
subscriber: where the response happen. Subscriber
should specify methods to respond to events. These
methods should take the same type of arguments as
the delegate. Subscriber then add this method to
publisher's delegate.
Therefore, when the event happen in publisher,
delegate will receive some event arguments (data, etc),
but publisher has no idea what will happen with all
these data. Subscribers can create methods in their
own class to respond to events in publisher's class, so
that subscribers can respond to publisher's events.
46 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Using Delegates with Events



How Events work with Delegates?
» Delegates are used to reference a method. An Event is
associated with Event Handler using Delegates. When an
Event raise, it sends a signal to delegates and delegates
executes the right functions.
What is Publisher-Subscriber Model?
» There are two parts in any event handling program. One
part is Publisher that contains definition of events and
delegates and another part is Subscriber that accepts the
event and provides an event handler.
The events are declared and raised in a class and
associated with the event handlers using delegates within
the same class or some other class. The class containing
the event is used to publish the event. This is called
the publisher class.
47 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1



Some other class that accepts this event is called
the subscriber class. Events use the publishersubscriber model.
A publisher is an object that contains the definition of
the event and the delegate. The event-delegate
association is also defined in this object. A publisher
class object invokes the event and it is notified to other
objects.
A subscriber is an object that accepts the event and
provides an event handler. The delegate in the
publisher class invokes the method (event handler) of
the subscriber class.
48 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Event Handlers (in general)


Unfortunately, many authors writing about events use
the term, "event handler", in reference to both (1) the
delegate upon which an event is based, and (2) a
method called by the delegate when the event is raised.
In order to avoid confusion resulting from this state of
affairs, this course uses the expression, "event
handler," only in reference to the delegate, while using
the expression, "event handling method," in reference
to any method registered with the delegate.
You can define your own event handlers (delegates), or
you can use one of the event handlers provided by the
.NET Framework (i.e., System.EventHandler, or the
generic System.EventHandler<TEventArgs>).
49 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1





The following sample event declaration make use of a
custom event handler rather than using a Frameworkprovided event handler.
Consider the following:
Line 1: public delegate void MyDelegate(
string whatHappened);
Line 2: public event MyDelegate MyEvent;
Line 1 declares a delegate type for which any method
can be assigned — provided that the method returns
void and accepts a single string argument.
Line 2 declares an event in terms of the delegate type.
Notice that the event (which is named MyEvent) is
declared very much like a method declaration — but
with its data type specified as the delegate type.
50 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Raising an Event



The event member itself just holds the event handlers
that need to be invoked. Nothing happens with them
unless the event is raised. You need to make sure there
is code to do just that, at the appropriate times.
Raising the event should generally be a two step
process. The first step would be to check to see if there
are any subscribers. The second step is to raise the
event, but only if there are any subscribers.
If there are no subscribers, then the delegate will test
to null. The following logic raises the event, but only if
the event has any subscribers.
if (MyEvent != null)
{
MyEvent(this, EventArgs.Empty);
}
51 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2



There is a possibility that the event could be cleared
(by code executing in another thread) between the test
for null and the line that actually raises the event.
This scenario constitutes a race condition. So it is
recommended to create, test, and raise a copy of the
event's event handler (delegate), like this:
MyEventHandler handler = MyEvent;
if (handler != null)
{
handler (this, EventArgs.Empty)
}
Events can have multiple subscribers — each of which
is called, in turn, by the delegate when the event
handler is invoked by the [handler (this, eventArgs)]
line.
52 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Declaring Events




To declare an event inside a class, first a delegate type
for the event must be declared. For example,
public delegate string MyDel(string str);
Next, the event itself is declared, using the event
keyword:
event MyDel MyEvent;
The preceding code defines a delegate named MyDel
and an event named MyEvent, which invokes the
delegate when it is raised.
Steps for creating and calling the event:
» The event is an instance of a delegate
» Since an event is an instance of a delegate, then we have
to first define the delegate.
» Assign the method / methods to be executed when the
event is fired (Calling the delegate)
» Fire the event (Call the delegate)
53 - Prof . Yousef B. Mahdy, Assuit
Software Development
Important Fact about Events







An Event is created using event keyword.
An Event has no return type and it is always void.
All events are based on delegates.
All the published events must have a listening object.
All Events should be defined starting with “On”
keyword.
Let’s understand all these theory using Programming
Example. Before seeing the programming examples you
must know the sequential steps to manipulate events.
Step 1: Define a Delegate
Step 2: Define an Event with same name of Delegates.
Step 3: Define an Event Handler that respond when
event raised.
Step 4: You must have method ready for delegates.
54 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Example1

This program simply adds two numbers. Only condition
is if the sum of number is odd it fires an event that
print a message using delegates.
55 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
56 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2





1)-Delegate Created:
public delegate void dg_OddNumber();
2)-Event Created
public event dg_OddNumber ev_OddNumber;
3)-ev_OddNumber() event gets executed if the odd
number is found.
4)-In the AddTwoNumbers class there is a
function void Add() that adds two numbers. If the sum
of
the
number
is
Odd
it
raised
an ev_OddNumber event. In the main function
this ev_OddNumber event handler calls the delegates.
5)-Then finally delegate executes the function.
static void EventMessage(){
Console.WriteLine("********Event Executed :
This is Odd Number**********");}
57 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Example

A Asd class creates events at a tick of 3 seconds, and
a Listener class hears the Asd ticks and prints "HEARD
IT" to the console every time it receives an event.
58 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
59 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Built in Delegates in C#

In the previous part we learned to create custom
events in c#. In this part you will know how to use in
built delegates in c#. Microsoft provides 2 built in
delegates to work with:
public delegate void EventHandler(object sender,
EventArgs e);
public delegate void EventHandler<TEventArgs>(
object sender, TEventArgs e);

These built in delegates helps you to write event
handling code with ease. With these delegates you can
pass one or more than one value to event handler.
When you raise event you must follow the discipline
and pass required parameters to delegates.
60 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Example
61 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
62 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
Explanation: In this program, I have used built in
delegates in c#.
 1)- Declare built in delegates:
public event EventHandler<EventArgs> ev_OddNumber;
 2)- Raised Event:
ev_OddNumber(this, EventArgs.Empty);
 this
denotes
the
current
instance
of
class.
EventArgs.Empty tells that there is empty value in
parameter.
 3)- Initialize Events in Main function:
a.ev_OddNumber += EventMessage;
 4)-Calls the methods with required parameters.

static void EventMessage(object sender, EventArgs e){
Console.WriteLine("***Event Executed : This is Odd
Number***"); }
63 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3


In the above program the events doesn’t return any
value. Now, look for the next modified program that
returns a value with EventArgs.
A slightly more complicated example is if the event has
information passed with it, such as mouse coordinates
for a mouse event or which key is pressed for a
keypress event. To do this you need to create an
appropriate class derived from the EventArgs class and
then set an instance of it before raising the event.
64 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4
65 -
Prof . Yousef B. Mahdy, Assuit
Software Development
5
66 -
Prof . Yousef B. Mahdy, Assuit
Software Development
6



Let’s understand this example:
1)-I have created a custom OddNumberEventArgs class
that inherits the EventArgs. This class simply set the
parameter value to sum variable:
2)-Now, created event ev_OddNumber using this class.
public event EventHandler<OddNumberEventArgs>
ev_OddNumber;
67 -
Prof . Yousef B. Mahdy, Assuit
Software Development
7
3)-Pass
required
parameter
when
called
this
event(Raised Event):.
ev_OddNumber(this, new OddNumberEventArgs(result));
 Now
in
the
EventMessage()
function
; OddNumberEventArgs e has a value.

68 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Event and Anonymous methods



Anonymous methods allow you to pass a code block
rather than the name of the method.
If you will not have to unsubscribe to an event later, you
can use the addition assignment operator (+=) to attach
an anonymous method to the event. In the following
example, assume that an object named publisher has an
event
named
RaiseCustomEvent
and
that
a CustomEventArgs class has also been defined to carry
some kind of specialized event information. Note that the
subscriber class needs a reference to publisher in order to
subscribe to its events.
Notice that rather than registering an instance of a
delegate, you use the keyword delegate, followed by the
parameters that would be passed to your method,
followed by the body of your method encased in braces
and terminated by a semicolon.
69 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
70 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Event and Lambda expressions





Lambda expressions are functions with a different
syntax that enables them to be used in an expression
context instead of the usual object-oriented method of
being a member of a class. This means that with a
single syntax, we can express a method definition,
declaration, and the invocation of delegate to execute
it, just as anonymous methods can, but with a more
terse syntax.
A lambda expression looks like this:
j => j * 42
This means "using j as the parameter to the function, j
goes to the result of j*42." The => can be thought of
as "goes to" for both this and for a projection that was
declared like this:
j => new { Number = j*42 };
71 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
You can use a lambda expression wherever a delegate
instance is expected. This includes using a lambda
expression when defining an event handler:
d.Barked += (s, e) => {
Console.WriteLine("My dog says {0}", e); };

Lambda expressions can be used to tie event handling
code to an event.
 Lambda expressions assume implicit data typing which
means you do not have to figure out the data type of
the event’s e parameter—the compiler will do it for you.
this.Click += (s,e) => {
MessageBox.Show(((MouseEventArgs)e).Location.ToStri
ng());};

72 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Example-Normal
73 -
Prof . Yousef B. Mahdy, Assuit
Software Development
with lambda expressions
74 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1


Most folks would agree that this looks cleaner, and is
easier to follow. The one time this doesn't work is when
you need to be able to clear event handlers as well as
assign them. There are two methods to do this.
But if you need more granularity, or don't have access
to the source, you can assign the lambda expression to
a variable (e.g., "handleAlarm") before you assign it as
an event-handler, like so:
75 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2

Note that you need to assign the handleAlarm variable
to null first, because otherwise the compiler complains
about the first line of the lambda expression: it thinks
that you're trying to muck about with an uninitialized
variable. This is only sort of true, but to work around it,
just assign the variable to null when you declare it.
76 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Exercises-1



Write a program for Online Attendance. The conditions
are as follow:
User provides their name as Input and then application
show message to “Welcome to their Name”.
Asd1, Asd2 and Asd3 are banned for the organization.
So, when any user enters Asd1, Asd2 and Asd3 as user
name, the application raised an event and fire alarm as
well as sends email to administration.
77 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
78 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
79 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Exercises-2

Write a repeated alarm program that uses delegates to
notify anyone (who is interested) every three seconds.
80 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Solution
81 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
82 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
83 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Exercises-3,5,5,5




3)-Write a countdown alarm program that uses delegates
to notify anyone who is interested that the designated
amount of time has passed. You'll need a class to simulate
the countdown clock that accepts a message and a
number of seconds to wait (supplied by the user). After
waiting the appropriate amount of time, the countdown
clock should call the delegate and pass the message to
any registered observers. Create an observer (subscriber)
class as well that echoes the received message to the
console.
4)- Rewrite the observer class in Exercise 1 to publish to
multiple handlers.
5)-Rewrite the observer class in Exercise 1 to use an
anonymous method.
6)-Rewrite the observer class in Exercise 2 to use a
lambda expression instead of an anonymous method.
84 -
Prof . Yousef B. Mahdy, Assuit
Software Development
Solution
85 -
Prof . Yousef B. Mahdy, Assuit
Software Development
1
86 -
Prof . Yousef B. Mahdy, Assuit
Software Development
2
87 -
Prof . Yousef B. Mahdy, Assuit
Software Development
3
88 -
Prof . Yousef B. Mahdy, Assuit
Software Development
4
89 -
Prof . Yousef B. Mahdy, Assuit
Software Development



Anonymous methods allow you to pass a code block
rather than the name of the method.
If you will not have to unsubscribe to an event later, you
can use the addition assignment operator (+=) to attach
an anonymous method to the event. In the following
example, assume that an object named publisher has an
event
named
RaiseCustomEvent
and
that
a CustomEventArgs class has also been defined to carry
some kind of specialized event information. Note that the
subscriber class needs a reference to publisher in order to
subscribe to its events.
Notice that rather than registering an instance of a
delegate, you use the keyword delegate, followed by the
parameters that would be passed to your method,
followed by the body of your method encased in braces
and terminated by a semicolon.
90 -
Prof . Yousef B. Mahdy, Assuit
Software Development
91 -
Prof . Yousef B. Mahdy, Assuit
Software Development