Delegate in C#

Delegate is a reference type method which holds the reference method.

"Delegates are use at run time".

Declare delegate below this keyword:

Public delegate void mydelegate(String s);

There are two types of delegate.

1. Single cast Delegate -"A single cast delegate contains reference to only one method at a time".

2. Multi cast Delegatec - "A multi cast delegate hold the reference of more than method and execute all the method. It wraps in the calling order".

Example of delegate program print to device.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.IO;  
  5.   
  6. namespace Delegates  
  7. {  
  8.     public class Program  
  9.     {  
  10.         static FileStream fstream;  
  11.         static StreamWriter swriter;  
  12.         public delegate  void printdata(String s); //apply delegate this program  
  13.         public static void Writeconsole(String str)  
  14.         {  
  15.             Console.WriteLine("", str);  
  16.         }  
  17.         public static void WriteFile(String s) // name method  
  18.         {  
  19.             fstream = new FileStream("C:\\Users\\KRISHNA SINGH\\Desktop\\Hi3.txt", FileMode.Append, FileAccess.Write); // Apply to system location for create file u can select any other location  for print file...and  u can create .doc file & .sxlx file & .pps file and more…  
  20.             swriter = new StreamWriter(fstream);  
  21.             s = s +"";a  
  22.             swriter.WriteLine(s);  
  23.             swriter.Flush();  
  24.             swriter.Close();  
  25.             fstream.Close();  
  26.         }  
  27.           
  28.         public static void DisplayData(printdata pmethod)  
  29.         {  
  30.             pmethod("");  
  31.         }  
  32.         public static void Main()  
  33.         {  
  34.             printdata pd = new printdata(Writeconsole);  
  35.             printdata f1 = new printdata(WriteFile);  
  36.             DisplayData(pd);  
  37.             DisplayData(f1);  
  38.             Console.ReadLine();  
  39.         }  
  40.     }  

Then run the program you seen blank console CMD just like as:



Then enter the Button.

Seen the output of this example of the delegate program.

Go to your system location in which location u given in program that this file print or create or not.
 
 
Ebook Download
View all
Learn
View all