C# Fundamentals - Delegates

Delegates

Delegate means 'a representative', just as it's meaning it's implementation is the same as well. You have a delegate representing a function of yours.
A delegate is a wrapper around a pointer to a function ( you might be familiar with function pointers in C++ ). These delegates are also type safe and also have some features that make it way more useful than just a function pointer which we will be going over.
To use delegates first we need to declare one, It's syntax basically looks like this : 
[<modifiers>] delegate [return type] <Name>( [Parameter list])
Eg:
public delegate int MyDelegate(string str);
Delegates can be defined directly under a namespace or under a class.
Delegates can point to either static or instance methods.
To use a delegate we have to first instantiate a delegate. To Instantiate a delegate we have to pass a method as parameter or directly assign.
MyDelegate myDelegate = new MyDelegate(method); // As parameter
MyDelegate myDelegate = method // Directly assigning the method
Can call function with invoke member function or normally as well but using Invoke is better because it shows that it is a delegate (my opinion) 😇.
myDelegate(); // Option 1
myDelegate.Invoke(); // Option 2
So now we will look at how a delegate is used as a callback ( most common use ).
using System;
namespace BitShiftProductions
{    
    public delegate void CallBack(int i);
    public class ClassA
    {
        public void LongRunningTask(CallBack cb)
        {
             for(int i=0;i<100;i++)
               cb(i);
        }
    }    
    public class Program
    {
        static void UseProgressValue(int x)
        {
            Console.WriteLine("Processed : " + x + "%");
        }
        public static void Main(string[] args)
        {
            ClassA objA = new ClassA();
            CallBack callback = new CallBack(UseProgressValue);
            objA.LongRunningTask(callback);
        }
    }
}
Output:
Processed : 0%
Processed : 1%
Processed : 2%
Processed : 3%
.
.
.
Processed : 100%
Now I will introduce you to two properties Method & Target, They use reflection to provide us some details.
Method property :- Has data about the method being held and will display the function name and parameter list when printed.
Target property :- Has data about the object that the method is from. If the method is a static function then it will return null, otherwise it will display object's class data.
Now we will look at a more real world example:
using System;
namespace BitShiftProductions
{    
    public delegate bool MeetsCriteria(int[] intValues);
    public delegate void TargetTester();
    public class IntegerMaster
    {
        private int[] integers;
        public IntegerMaster(int[] ints){integers = ints;}
        public void DoMyIntegersMeetCriteria(MeetsCriteria funcVal)
        {
             if(funcVal(integers))             
                 Console.WriteLine("Meets Criteria For : " + funcVal.Method);             
            else
                Console.WriteLine("Does Not Meet Criteria" + funcVal.Method);
        }
    }    
    public class Program
    {
        static bool AreMultiplesOfTwo(int[] integers)
        {
            for(int i=0;i<integers.Length;i++)
            {
                if(integers[i]%2 != 0)
                    return false;
            }
            return true;
        }
        static bool GreaterThanTen(int[] integers)
        {
            for(int i=0;i<integers.Length;i++)
            {
                if(integers[i] <= 10)
                    return false;
            }
            return true;
        }
        static void PrintValues(TargetTester tester)
        {
            Console.WriteLine("Method of : " + tester.Target);
            tester.Invoke();
        }
        public static void Main(string[] args)
        {
            IntegerMaster ima = new IntegerMaster(new int[]{6,18,2,14,32,64,44});
            ima.DoMyIntegersMeetCriteria(AreMultiplesOfTwo);
            ima.DoMyIntegersMeetCriteria(GreaterThanTen);
            PrintValues(ima.PrintIntegers);
        }
    }
} 
Output:
Meets Criteria For : Boolean AreMultiplesOfTwo(Int32[])
Does Not Meet CriteriaBoolean GreaterThanTen(Int32[])
Method of : BitShiftProductions.IntegerMaster
Value at 0 = 6
Value at 1 = 18
Value at 2 = 2
Value at 3 = 14
Value at 4 = 32
Value at 5 = 64
Value at 6 = 44
Now let's look at what 'delegate chaining' is.
Delegate chaining is a feature that basically allows us to call a list of functions one after another in the order we added them and is a really useful feature especially when starting to work with events in C#.
For adding a new function to the delegate object 
syntax:
delegateObject += function;
For removing a previously added function from the delegate object 
syntax:
delegateObject -= function;
using System;
namespace BitShiftProductions
{    
    public delegate void Display();
    
    public class Program
    {
        static void PrintA(){Console.WriteLine("Printed A");}
        static void PrintB(){Console.WriteLine("Printed B");}
        static void PrintC(){Console.WriteLine("Printed C");}
        public static void Main(string[] args)
        {
            Display display = PrintA;
            display += PrintB;
            display += PrintC;
            display += PrintA;
            display();
            Console.WriteLine("Removing a Print A Function");
            display -= PrintA;
            display();
        }
    }
}
Printed A
Printed B
Printed C
Printed A
Removing Print A Function
Printed A
Printed B
Printed C
You can see that the last instance of PrintA was removed, not the first ,so removing the functions  acts in the form of a stack.
So whatever is added last is taken out first ( LIFO ).
Here is a section of code which is really important to remember while using delegates.
public delegate int GetValue();
static int Return5(){return 5;}
static int Return10(){return 10;}
public class Program
{
   public static void main()
   {
       GetValue getValue = Return5;
       getValue += Return10;
       int x = getValue();
       // x value will be 10
   }
}
The x value is 10 because that was the function that was added last, and when returning... that last function's return value is used.
Another useful feature is the 'Invocation list'.
There is a member function for delegates called ' GetInvocationList() ', It returns an array of delegates that are chained to that specific delegate object.
Eg:
Delegate[] displays = display.GetInvocationList();
for(int i=0;i<displays.Length;i++)
{
    ((Display)displays[i]).Invoke();
}
The above code basically gets an array of functions from the delegate object as type 'Delegate' and in order to use it as we did before, we have to cast it as type 'Display' to invoke it.
You somehow managed to get through all of that... now treat yourself to a snack.😌
For More C# Tutorials, go HERE.
Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders or unity development in general don't be shy and leave a message on my facebook page or down in the comments.