s

C# Delegates edit button Edit

author
Rakesh Kumar Sutar | calendar 21 January 2021 | 2578

Introduction

A delegate is an object which refers to a method or a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C . It provides a way which tells which method is to be called when an event is triggered.

Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hello_World
{
    class Program
    {
        public delegate void ExceptionLogger(Exception ex);
        static void Main(string[] args)
        {
            HelloWorld(ErrorLogConsole);
            HelloWorld(ErrorLogFile);
            HelloWorld(ErrorLogDB);
            Console.ReadLine();
        }

        public static void HelloWorld(ExceptionLogger log)
        {
            try
            {
                throw new Exception("deligate example");
            }
            catch (Exception ex)
            {

                log(ex);
            }
        }

        public static void ErrorLogConsole(Exception exception)
        {
            Console.WriteLine("\tConsole Logger");
            Console.WriteLine(exception.ToString());
        }

        public static void ErrorLogFile(Exception exception)
        {
            // Code to write error to file
            Console.WriteLine("\tFile Logger");
            Console.WriteLine(exception.ToString());
        }

        public static void ErrorLogDB(Exception exception)
        {
            // Code to write error to db
            Console.WriteLine("\tDB Logger");
            Console.WriteLine(exception.ToString());
        }
    }



}

    



Output