C# – Delegate

What the heck is a delegate?

Delegate:

– Function pointers
– Can be changed run-time
– Comes from System.Delegate

using System;

delegate void myDelegate(string name);

namespace delegatedis
{
    public class Program
    {
        static void women(string name){
            Console.WriteLine("Hi Miss "+name+"! Have a nice day!");
        }

        static void attackhelicopter(string name){
            Console.WriteLine("Hi Apache " +name+"! gl hf!");
        }
        
        public static void Main(string[] args)
        {
            myDelegate mydel;
            string name = "Jane Doe";
            mydel = women; // We can use mydel like it is a pointer.
            mydel(name);
            string name = "AH-64";
            mydel = attackhelicopter; 
            mydel(name);
            
        }
    }
}

Out:

Hi Miss Jane Doe! Have a nice day!
Hi Apache AH-64! gl hf!

Leave a Reply

Your email address will not be published. Required fields are marked *