Date post: | 05-Jul-2015 |
Category: |
Technology |
Upload: | niit-care |
View: | 523 times |
Download: | 0 times |
Slide 1 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
In this session, you will learn to:Use delegate
Types of delegates
Use events with delegates
Apply attributes
Use predefined attributes
Objectives
Slide 2 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
You can call the delegate by giving the name of the
delegate and by passing parameters, if required. Using delegates is similar to calling methods.
Using Delegate
Slide 3 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
The following example shows how to use a delegate:using System;
using System.IO;
// Program to write the data to the console and file
namespace Chapter12_Ex1
{
public class PrintToDevice
{
//Creating the variables of Stream classes
static FileStream FStream;
static StreamWriter SWriter;
//Defining a Delegate
//Method to send the string data to respective methods
Using Delegate (Contd.)
Slide 4 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
//removing the content from the buffer
SWriter.Flush();
SWriter.Close();
FStream.Close();
}
public delegate void PrintData(String s);
//Method to print a string to the console
public static void WriteConsole (string str)
{
Console.WriteLine("{0} Console", str);
}
//Method to print a string to a file
public static void WriteFile (string s)
Using Delegate (Contd.)
Slide 5 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
{
//Initializing stream objects
FStream = new FileStream("c:\\StoreData.txt", FileMode.Append, FileAccess.Write);
SWriter = new StreamWriter(FStream);
s= s + " File";
//Writing a string to the file
SWriter.WriteLine(s);
}
public static void DisplayData(PrintData PMethod)
{
PMethod ("This should go to the");
}
public static void Main()
Using Delegate (Contd.)
Slide 6 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
{
//Initializing the Delegate object
PrintData Cn = new PrintData (WriteConsole);
PrintData Fl = new PrintData (WriteFile);
//Invoking the DisplayData method with the Delegate object as the argument
//Using Delegate
DisplayData (Cn);
DisplayData (Fl);
Console.ReadLine();
}
}
}
Using Delegate
Slide 7 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Delegates are of two types and depending upon the requirement of the application the suitable type of delegate is selected.
Types of Delegates
Slide 8 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Types of Delegates (Contd.)
There are two types of delegates:Single-cast delegate
Multicast delegate
Slide 9 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
• A single-cast delegate derives from the System.Delegate class.
• It contains reference to one method only at a time.
Single-Cast Delegate
Slide 10 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Multicast Delegate
A multicast delegate derives from the System.MulticastDelegate class.
It contains an invocation list of multiple methods. In multicasting you create a single delegate that invokes multiple encapsulated methods.
You need to ensure the return type of all these delegates is same.
Multicast delegates hold the reference of more than one method therefore, if you call a multicast delegate it will executes all the methods it wraps in the calling order.
The multiple methods called by the delegate in this case should not return any value. Several multicast delegates are called consecutively and you cannot wait to get the return value from each of these methods.
Slide 11 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Just a minute
State whether the following statement is True or False.
Multicast delegates inherit from the System.Delegate.MulticastDelegate class.
Answer:False
Slide 12 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Working with Events
An event is an action or occurrence, such as clicks, key presses, mouse movements, or system generated notifications.
Applications can respond to events when they occur.
Slide 13 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Working with Events (Contd.)
The following figure shows the alarm event and handling of the event.
Clock Shows time.Time is 6 AM.
Alarm plays a sound, notifyingeveryone that it is 6 AM.
You hear the alarm.
You get up and get readyFor your school.
Slide 14 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Using Delegates with Events
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or other classes.
Events are part of a class and the same class is used to publish its events.
The other classes can, however, accept these events or in other words can subscribe to these events.
Events use the publisher and subscriber model.– A publisher is an object that contains the definition of the event
and the delegate. The association of the event with the delegate is also specified in the publisher class.
– A subscriber is an object that wants to accept the event and provide a handler to the event. The delegate of the publisher class invokes the method of the subscriber class.
Slide 15 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Using Delegates with Events (Contd.)
The following figure shows the mechanism used by the publisher and subscriber objects.
Let us understand the using delegates with events in detail.
Slide 16 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Using Delegates with Events (Contd.)
The implementation of an event includes: Events definition
Events subscription
Events notification
Slide 17 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Defining an Event:The definition of the event in a publisher class includes the declaration of the delegate as well as the declaration of the event based on the delegate. The following code defines a delegate named TimeToRise and an event named RingAlarm, which invokes the TimeToRise delegate when it is raised:
public delegate void TimeToRise();
private event TimeToRise RingAlarm;
Using Delegates with Events (Contd.)
Slide 18 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Subscribing to an Event:– The event of the publisher class needs to be associated with
its handler. – The event handler method is associated with the event using
the delegate.– When the publisher object raises the event, the subscribing
object associates the method, which needs to be called. – The requirement could be implemented using events. The
following code shows how the Student class subscribes to the event named TimeToRise:
Student PD= new Student();
RingAlarm = new TimeToRise(PD.WakeUp);
Using Delegates with Events (Contd.)
Slide 19 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Notifying Subscribers to an Event:– The subscriber object notifies the subscriber object to the
publisher object. The event is raised to notify the handler.– Write this block of code at a place from where you want to
notify the event to the subscribers of the event:
if (RingAlarm != null)
{
RingAlarm( );
}
Using Delegates with Events (Contd.)
Slide 20 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
• The methods that subscribe an event might expect some input to be passed.
• The event class can have these inputs at runtime on which the subscribing method works.
• You need to define the class that will pass the input to the event.
• Derive this class from System.EventArgs. To pass values to a subscribing method, you need to enclose the parameters in a single class.
• The single class supplies a special method called the accessor method to retrieve the value.
• This method is used to examine or modify the members of a class.
Passing Event Parameters
Slide 21 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Problem Statement:In an air-conditioner manufacturing company, the working time is from 9 AM to 6 PM. The management of the company is flexible and it allows workers to arrive to work late by 1 hour. The entry time of workers is recorded electronically in a log file when they enter the premises of the company. The application used for recording the attendance of each worker needs to log the appropriate information.
Help the company to design an application for logging attendance.
Demo: Attendance Log
Slide 22 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Solution:To design the application, you need to perform the following tasks:
1. Identify the technique that you will use in the application. This technique will allow you to call the respective methods dynamically to log the attendance entry.
2. Create a console-based application to implement the attendance log of workers.
3. Compile and execute the application.
Demo: Attendance Log (Contd.)
Slide 23 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
• An object is described by the values of its attributes. • An attribute is a declarative tag that is used to convey
information to runtime about the behavior of programmatic elements such as classes, enumerators, and assemblies.
• A declarative tag is depicted by square ([ ]) brackets placed above the definition of an element such as a class or a method.
• Attributes are used for adding metadata, such as compiler instructions and other information such as comments, description, methods, and classes to a program.
• The .NET Framework is equipped with a number of predefined attributes.
Introducing Attributes
Slide 24 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Attributes are applied to different elements of the code.
These elements include assemblies, modules, classes, structs, enums, constructors, methods, properties, fields, events, interfaces, parameters, return values, and delegates. Information about attributes is stored with the metadata of the elements they are associated with.
The following syntax enables you to specify an attribute:[attribute(positional_parameters,name_parameter
= value, ...)] element
The .NET Framework supports two categories of attributes to be used in C# programs:
Predefined
Custom
Applying Attributes
Slide 25 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
Some commonly used predefined attributes provided with .NET Framework are:
Conditional
WebMethod
DLLImport
Obsolete
Using Predefined Attributes
Slide 26 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
In this session, you learned that:– There are two types of delegates, Single-cast delegate and
Multicast delegate.– A single-cast cast delegate can call only one function.– Multicast delegate holds the reference of more than one
method.– Single-cast delegate derives from the System.Delegate
class and Multicast delegate derives from the System.MulticastDelegate class.
– Events are the messages sent by an object to indicate the occurrence of an event.
– Events use the publisher and subscriber model.– A publisher is an object that maintains its internal state.
Summary
Slide 27 of 27Session 17Ver. 1.0
Object-Oriented Programming Using C#
– A subscriber is an object that registers an interest in an event.
– An attribute is a declarative tag that is used to convey information to runtime about the behavior of programmatic elements such as classes, enumerators, and assemblies.
– The .NET Framework supports two categories of attributes to be used in C# programs: predefined and custom.
– Predefined attributes are supplied as part of the Common Language Runtime (CLR), and they are integrated into .NET.
Summary (Contd.)