Delegates in C#.

Suleiman Abdullah
3 min readOct 6, 2024

--

Objective: Delegates in C#.

Delegates are variable which store method in it.

How Delegates store method Suleiman?

Delegate are variables which define method signature then that signature used to create Independent variable for signature of delegate method. That method signature variable used to store method which used as reference to call stored method.

Lets go to the step below then come back to read the above descriptions.

To define Delegate we start with modifier then use keyword delegate, then specify a return type of method followed by method name, last we finish by add double parenthesis with either one or more parameters or nor parameter at all.

Note: This is only define a delegate signature ,it wont do anything on its own.

Now we need to create a variable for method signature of the delegate and give it a name.

Now lets say We have a normal method which have same signature, the method we store does not need to be the same as our delegate method signature, it can take different name but the signature must match with delegate method(void without parameter or if return type with game object parameter).

To store this method to delegate we use delegate signature variable and assign to above method with its name without double parenthesis.

How do we call this method using delegate method signature variable ?

We type delegate method signature variable just like we call normal method with double parenthesis.

Best Practice when call delegate

If delegate is not assign to any method it will be null.

So best practices is to null check before calling delegate.

Multicast in Delegate.

We can use single delegate to invoke multiple method stored in single method.

To store multiple delegate we use add sign after equal sign follow by the name of method.

Note: Make sure the method match delegate method signature.

Best Practice When use multicast in delegate

We need to unsubscribe when we destroy the game object.

To unsubscribe to register method we use minus sign ,the best place is Disable.

Delegate can change method at run time.

See you into the next one.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development