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.

advertisement
advertisement

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

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.