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. namespace Delegates
  6. {
  7. public class Program
  8. {
  9. static FileStream fstream;
  10. static StreamWriter swriter;
  11. public delegate void printdata(String s); //apply delegate this program
  12. public static void Writeconsole(String str)
  13. {
  14. Console.WriteLine("", str);
  15. }
  16. public static void WriteFile(String s) // name method
  17. {
  18. 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…
  19. swriter = new StreamWriter(fstream);
  20. s = s +"";a
  21. swriter.WriteLine(s);
  22. swriter.Flush();
  23. swriter.Close();
  24. fstream.Close();
  25. }
  26. public static void DisplayData(printdata pmethod)
  27. {
  28. pmethod("");
  29. }
  30. public static void Main()
  31. {
  32. printdata pd = new printdata(Writeconsole);
  33. printdata f1 = new printdata(WriteFile);
  34. DisplayData(pd);
  35. DisplayData(f1);
  36. Console.ReadLine();
  37. }
  38. }
  39. }

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.