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.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
-
- namespace Delegates
- {
- public class Program
- {
- static FileStream fstream;
- static StreamWriter swriter;
- public delegate void printdata(String s);
- public static void Writeconsole(String str)
- {
- Console.WriteLine("", str);
- }
- public static void WriteFile(String s)
- {
- fstream = new FileStream("C:\\Users\\KRISHNA SINGH\\Desktop\\Hi3.txt", FileMode.Append, FileAccess.Write);
- swriter = new StreamWriter(fstream);
- s = s +"";a
- swriter.WriteLine(s);
- swriter.Flush();
- swriter.Close();
- fstream.Close();
- }
-
- public static void DisplayData(printdata pmethod)
- {
- pmethod("");
- }
- public static void Main()
- {
- printdata pd = new printdata(Writeconsole);
- printdata f1 = new printdata(WriteFile);
- DisplayData(pd);
- DisplayData(f1);
- Console.ReadLine();
- }
- }
- }
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.