C# - SPLessons

C# Delegates and Events

Home > Lesson > Chapter 15
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Delegates and Events

C# Delegates and Events

shape Description

Delegate in C# is a class, which have same functionality like pointers. They hold reference to function or method with compact-able signature. This is called as encapsulating the method.Delegate is a reference type variable used for implementing call back methods and events.

shape Syntax

Delegate keyword is used to create a delegate, followed by return type and method signature public delegate int FindResult(object obj1, object obj2);

shape Example

Delegate with Static Function: [csharp] using System; namespace SpLessons { // Delegate Specification public class MyDelegate { public delegate void LogHandler(string message); // The use of the delegate is just like calling a function directly, public void Process(LogHandler logHandler) { if (logHandler != null) { logHandler("Start"); } if (logHandler != null) { logHandler ("End"); } } } // Sample Application to use the defined Delegate public class SampleApplication { // Static Function: To which is used in the Delegate. To call the Process() // function, we need to declare a logging function: Logger() that matches // the signature of the delegate. static void Logger(string s) { Console.WriteLine(s); } static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate (); // Create an instance of the delegate, pointing to the logging function. MyDelegate.LogHandler myLogger = new MyDelegate.LogHandler(Logger); myDelegate.Process(myLogger); } } } [/csharp] Output:

shape Example

Delegate with Calling Member Functions Example: [csharp] using System; using System.IO; namespace SpLessons { public class MyDelegate { // Declare a delegate that takes a single string parameter public delegate void LogHandler(string message); // The use of the delegate is just like calling a function directly public void Process(LogHandler logHandler) { if (logHandler != null) { Console.WriteLine("Start"); } if (logHandler != null) { Console.WriteLine ("Stop"); } } } // The FileLogger class merely encapsulates the file I/O public class FileLogger { FileStream fileStream; StreamWriter streamWriter; // Constructor public FileLogger(string filename) { fileStream = new FileStream(filename, FileMode.Create); streamWriter = new StreamWriter(fileStream); } // Member Function which is used in the Delegate public void Logger(string s) { streamWriter.WriteLine(s); } public void Close() { streamWriter.Close(); fileStream.Close(); } } // Main() is modified so that the delegate points to the Logger() // function on the fl instance of a FileLogger. public class SampleApplication { static void Main(string[] args) { FileLogger fl = new FileLogger("process.log"); MyDelegate myDelegate = new MyDelegate (); // Create an instance of the delegate, pointing to the Logger() // function on the fl instance of a FileLogger. MyDelegate.LogHandler myLogger = new MyDelegate.LogHandler(fl.Logger); myDelegate.Process(myLogger); fl.Close(); } } } [/csharp] Output:

Events

shape Description

Events are user action which tells the user that some action has been performed. For Example:On click of a button a button-click-event notification is sent to window hosting button. Before discussing about events please look in to delegates because events are generated using delegates.

shape Syntax

[csharp] [attributes] [modifiers] event type member-name {accessor-declarations}; [/csharp] Where attributes (optional) -> Optional declarative information. For more information on attributes and attribute classes, see "C# Attributes". modifiers (optional) -> Optional modifiers includes abstract, new, override, static, virtual, extern, one of the four access modfiers. type -> The delegate to which event is associated. declarator -> The name of the event. member-name -> The name of the event. accessor-declarations (optional) -> Declaration of the accessors, which are used to add and remove event handlers in client code. The accessor functions are add and remove. It is an error to define one but not the other.

Steps to create an event

shape Steps

1. Before creating an event, ensure that there is a delegate to use with the event keyword. If the event is predefined, in the .NET Framework.For example, then student of the event need only know the name of the delegate. 2. Create a class that contains:
  • An event created from the delegate.
  • Methods that call the event. These methods can be overridden by some base class functionality.
3. Create one or more classes that connect methods to the event. Each of these classes will include:
  • One or more methods, using the += and -= operators, with the event in the base class.
  • The definition of the method(s) that will be associated with the event.
4. How to use the event:
  •  Create an object of the class that contains the event declaration.
  •  Create an object of the class that contains the event definition, using the constructor that you defined.

shape Example

[csharp] using System; namespace SpLessons { public delegate void EventHandler(); class Program { public static event EventHandler object; static void Main() { object += new EventHandler(Apple); object += new EventHandler(Mango); Apple.Invoke(); } static void Apple() { Console.WriteLine("Apple "); } static void Mango() Console.WriteLine("Mango"); } } } [/csharp]