Breaking News

Friday 1 March 2019

Delegate Basic in C#

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

namespace DelegatesBasic
{
    //step 3
    //syntax for creating delegate.
    public delegate void HelloFunctionDelegate(string message);

    class Program
    {
        static void Main(string[] args)
        {
            //step 1
            //A delegate is a type safe function pointer


            //step 4
            //to run a delegate create its object just like we use to create the object of a class
            // and here its very simlar to the class.
            HelloFunctionDelegate del = new HelloFunctionDelegate(Hello); // this is how a delegate points to a function.
         
            //step 5
            del("hello from delegate....");

            //what I have done above is that just created a delegate's object and pass the function name into its constructor
            //now delegate know which function it needs to point/invoke by passing its name.
            // and then I am just passing a string message into the delegate object which is required by the Hello() method.

            Console.ReadKey();
        }
        //step 2
        public static void Hello(string strMessage) {
            Console.WriteLine(strMessage);
        }
    }
}

Read more ...
© 2013 Post by repter_x