C# Program to Implement Delegates
Posted by Superadmin on August 14 2022 03:26:27

C# Program to Implement Delegates

 

 

This is a C# Program to implement delegates.

Problem Description

This C# Program Implements Delegates.

Problem Solution

Here the delegate is created first and some data is displayed using the delegate.

Program/Source Code

Here is source code of the C# Program to Implement Delegates. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Implement Delegates
 */
using System;
using System.IO;
delegate void delegatewriter(string message);
class delgwriter
{
    StreamWriter w;
    public delgwriter(string path)
    {
        w = File.CreateText(path);
    }
    public void display(string msg)
    {
        w.WriteLine(msg);
    }
    public void Flush()
    {
        w.Flush();
    }
    public void Close()
    {
        w.Close();
    }
}
class Test
{
    static delegatewriter delgwri;
    static void display(string s)
    {
        Console.WriteLine(s);
    }
    static void Main(string[] arg)
    {
        delgwriter x = new delgwriter("log.txt");
        delgwri += new delegatewriter(display);
        delgwri += new delegatewriter(x.display);
        delgwri("C");
        delgwri("C++");
        delgwri("Java");
        x.Flush();
        x.Close();
        Console.Read();
    }
}
Program Explanation

This c# program is used to implement delegates. We are opening the file using delgwriter() function.

 

In delgwriz() function the createtext() function is used to create or open a file for writing utf-8 encoded text. Then in display() function print the message in ‘msg’ variable using writeline() function.

Then flush() function is used to clear buffers for this stream and causes any buffered data to be written to the file. Here the delegate is created first and some data is displayed using the delegate.

Runtime Test Cases
 
C
C++
Java