Delegates in C#


A delegate in C# is a reference to the method. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Let us see how to declare delegates in C#.

delegate <return type> <delegate-name> <parameter list>

Let us see an example to learn how to work with Delegates in C#.

Example

 Live Demo

using System;
using System.IO;
namespace DelegateAppl {
   class PrintString {
      static FileStream fs;
      static StreamWriter sw;
      // delegate declaration
      public delegate void printString(string s);
      // this method prints to the console
      public static void WriteToScreen(string str) {
         Console.WriteLine("The String is: {0}", str);
      }
      // this method prints to a file
      public static void WriteToFile(string s) {
         fs = new FileStream("c:\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // this method takes the delegate as parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps) {
         ps("Hello World");
      }
      static void Main(string[] args) {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}

Output

The String is: Hello World

Updated on: 23-Jun-2020

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements