Software & Finance





C# - Delegates





C# delegates are like pointers in C++ and it does use the word called delegate. In the following line, it does look like a function declaration along with the keyword delegate. Here Shape is the function pointer type definition with function signature of void <FunctionName>();

 

        public delegate void Shape();  // Returns nothing and takes no arguments

        public delegate bool MyStringFunction(string s); // Returns bool and takes string as an input

 

 

With the same signature we have to write functions and assign it to delegate definition shown below.

 

           Shape ptr = new Shape(d.Rectangle);

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Basics

{

    class Drawing

    {

        public delegate void Shape();

 

        public void Rectangle()

        {

            Console.WriteLine("This is Rectangle");

        }

 

        public void Square()

        {

            Console.WriteLine("This is Square");

        }

 

        public void Circle()

        {

            Console.WriteLine("This is Circle");

        }

 

        static void Main(string[] args)

        {

            Drawing d = new Drawing();

 

            // Shape is like a fuction pointer in C++

            // Shape [] is assigned with 3 functions with same function sigature

            Shape [] parray = { new Shape(d.Rectangle),

                                new Shape(d.Square),

                                new Shape(d.Circle)

            };

 

            // call the functions using delegates which is function pointers in C++

            parray[0]();

            parray[1]();

            parray[2]();

        }

    }

}

Output


 

This is Rectangle

This is Square

This is Circle