What are Delegates? (C# Basics, Lambda, Action, Func)

Unity Events and Delegates Guide for beginners - VionixStudio

private delegate void MyDelegate(); //declaration of a Delegate
private MyDelegate _myDelegate;     //declaration of a Delegate variable

 private void Awake() {
     _myDelegate= MyFunction;       //passing the function MyFunction to Delegate.
 }

	private void MyFunction(){}       //function matching the Delegate Template

void Start()
{
    _myDelegate();                  //calling the Delegate
}

Things to note about Delegates

  1. Function assigned to a Delegate should match the template.
  2. When you assign the function no () is required.
  3. You can assign more than one function to a Delegate.
  4. It’s advised to check if the Delegate is not Null before calling it.

Null check a Delegate

As mentioned above its better to check if the Delegate is Null before calling it.

You can simply use an if statement to do that

_myDelegate?.Invoke();

What are Events in C#?

Events are a type of delegates that can only have a void return type. Events have some restrictions on how to use them.

An event can be declared using an Event keyword and needs to be of type Delegate.

Here is a sample Event

delegate void my_Delegate();                  //declaration of a Delegate
event my_Delegate my_event;                 //declaration of an Event of type my_Delegate

Any event in C# is a multi-cast Delegate. So, it can be subscribed by multiple functions. But an event can near be triggered from outside its own class.