Friday, January 7, 2011

Using Delegate in Console application:.

You can call the delegate by giving the name of the delegate and by passing parameters, if required. Using delegate is similar to calling methods.
Consider a situation where you need to print information to a file and a screen. There is some common information that needs to go to the file and to the screen. There is some specific information for both. The methods to print the information to the file andscreen are different. You can call these methods at runtime by passing the common information.

The following example shows how to use a delegate:
using System;
using System.IO;

// program to write the data to the console and file

namespace delegate1
    public class PrintToDrive
        //creating the variables of stream class
        static FileStream  FStream;
        static StreamWriter SWriter;

        //Defining a Delegate

        public delegate void PrintData(string s);

        //Method to print a string to the console
        public static void WriteConsole(string str)
            Console.WriteLine("{0} console",str);

        // Method to print a string to a file
        public static void WriteFile(string s)
            //initializing stream object

            FStream = new FileStream ("c:\\StoreData.txt",FileMode.Append ,FileAccess .Write );

            SWriter = new StreamWriter (FStream);
            s = s + "File";

            //writing a string to the file
            SWriter.WriteLine (s);

            //removing the content from the buffer
            SWriter .Flush ();
            SWriter .Close ();
            FStream .Close ();

        //Method to send the string data to respective methods

        public static void Displaydata(PrintData pmethod)
            pmethod ("this should go to the");

        public static void Main()
            //initializing the delegate object

            PrintData cn = new PrintData (WriteConsole);
            PrintData F1 = new PrintData (WriteFile);

            // invoking the DisplayData method with the Delegate object aa the argument

            Displaydata (cn);
            Displaydata (F1);
Note: - The WriteConsole ( ) and WriteFile( ) methods are used to write the information to the screen and to the file. The delegate variable PrintData is used to refer to the WriteConsole ( ) and WriteFile( ) methods.

1 comment:

Anonymous said...


Recent Posts