C# delegates, I love you ...

For confirmed devs, it can be obvious, but for people like me who come from more “simplistic” languages (javascript, ActionScript, Java, etc), their true use discovery just made me cheer like a soccer fan during finals, and say … “goddamn it, why didn’t I know this earlier ?”

So I wanted to share the experience, so other people who learn C# will not make the same mistake as me :slight_smile:
(I’m not claiming to know everything about delegates, so if this post need corrections, feel free)

In short, delegates. That is the basic.
You can read the page, but to sum it up, delegate is attributing a method execution to a variable at runtime. So in short, imagine you have a huge core function, SpawnEnemy(), where at some point you want to spawn very different enemies with very different behaviours, under very different conditions. Instead of writing a 5000 lines long if () {} else if () {} else if () {} crap sauce, you just insert a delegate (let’s say, OnSpawnEnemy()). Then for each new SpawnEnemy() called, you can reattribute the OnSpawnEnemy delegate to a different function from another script, depending on which condition is met (indeed, OnSpawEnemy reattribution has to happen before its execution).
For example, at time 25f, some manager reattributes OnSpawnEnemy = CreateTrolls to create Trolls, at time 50f OnSpawnEnemy = CreateOrcs to create Orcs, etc,. Then whenever I call OnSpawnEnemy(), it will create the defined type of enemy.

But I found this MSDN tutorial page wasn’t doing much justice to their real power …

Two things I found which were totally awesome :

  1. Anonymous delegates : I don’t know if it’s some coder porn syndrome, but I love this one. In short, instead of hardwriting tons of different separate functions for each delegate case you want, you just write *OnSpawnEnemy = delegate { //stuffToDo }* . It’s a must for structure visibility. The only downside is that what’s inside the delegate doesn’t save conditional variables. For example : *for (int i = 0; i < 5; i++) OnSpawnEnemy = delegate { Debug.Log(i); }* will always display *4*. So you have to hardwrite variables. But it’s not a big deal really, as you’re not supposed to create super complicated anonymous delegate bodies (for debugging’s sake).
    What I like with anonymous delegates is that you can “hack” a core behaviour at any given time under whatever condition you want, just by writing a quick subscript. Visually, the fact of not declaring a whole new function will 100% fit the very contextual nature of the change, keeping your core architecture clean.

  2. the most important one : the += and -= operators. So let’s take our OnSpawnEnemy(). What if at some time, I want to spawn 4 Trolls AND 4 Orcs ? You just write :

OnSpawnEnemy += CreateTrolls;
OnSpawnEnemy += CreateOrcs;
OnSpawnEnemy(4);

And if later on, you don’t want to spawn Orcs anymore, just write :

OnSpawnEnemy -= CreateOrcs;

As said in 1), the real power here is to make you able to hack a generic, core function. When you have a highly complex architecture, it’s always better to merge redundant operations into core functions, so you trim the code noise for better clarity. It’s better for debugging, too. For example with Orcs and Trolls, instead of creating 2 separate full creation functions, you merge every critical common code into SpawnEnemy (like memory management, common asset instancing, common variables like HP, strength etc declarations, etc). And then you create the “exoticisation” of your enemy in specific, separate functions that you integrate in the core one, like written above.
At first, I was using virtual/override methods to fit each different injection. But what if I wanted to create 2 merged overrides within the same virtual entry ? I had to create another virtual into the first virtual, or one after another, etc … VIRTUALCEPTION ! a nightmare :slight_smile: And most of all, a huge waste of code space as you have to declare your empty virtual functions …
But here with delegates, no need to declare useless virtual empty functions… just to call OnSpawnEnemy() (+test if null beforehand), and add/retrieve as many hacks as I want with a single += operator, from wherever I want.


Conclusion : I don’t know if delegates were created (or function pointers in C) with videogames in mind, but it’s clearly a must for behaviour management, and totally fits the nature of videogames code dynamic logic.
Want to add a powerup to that punch ? No problem. *OnStrikePunch += PowerUp;*
Want to retrieve that wall bounce testing for that ball ? No problem. *OnBallHitTest -= TestWalls;*

I can also see how powerful delegates can be in a collaborative environment. The architect creates core code “waypoints” as delegates, and then each dev can control what type of behaviour he wants to add inside that waypoint.

Anyway, just to wanted to share my nerdiness for delegates, but feel free to add anything you want about them, like other particularly useful scenarios, etc.
Oh and did I mention that delegate were fast ? :wink:
(That was my first fear when I realized how powerful they were)

7 Likes

Now read up on Lambda’s, Action Func.

1 Like

But I’m only lvl 33 … :stuck_out_tongue:
Thanks :wink: C# is really feeling like an endless Ali Baba’s cave for efficiency, stability AND simplicity. Why isn’t it more widespread in videogame dev jobs ?
(granted I didn’t really extensively test C++, but it seems like C# is evolving much faster)

That’s one of the reasons I completely switched to C# within Unity. I wish I could switch to C# in my day to day work, too :slight_smile:

Now lets talk about the bad side of delegates… They play havoc with the GC unless you know what you are doing. Lets go through 2 specific use cases:

  1. You add a delegate that references something large in memory (Texture2D for example). You hook this delegate up to an event and then it’s all good. Nice callbacks and everything. Now for some reason the container for the delegate goes away (the game object holding the Texture2D). You have never removed the reference to the delegate on the event. The Texture2D is still referenced. It will stay around until the class holding the event goes away. As it’s very common for these classes to be ‘Managers’ of some type it’s likely that your Texture will never be GC’d :frowning:

  2. You use anonymous delegates, the delegate references a Texture2D. There is NO WAY to remove the delegate from an event. You are back in situation 1.

For the forthcoming GUI system we decided to implement ‘better’ delegates that work by holding weak references and play nice with the GC. They will work throughout unity and can also be serialised. They are not ready for release yet but I think they are pretty cool.

If you are going to use c# delegates try and avoid anon delegates. Also be really careful with memory overhead in using some of c#'s ‘nice’ features like linq and foreach and the like. Use the profiler and make sure to keep your allocations in check.

8 Likes

Delegates are really powerful but use it wisely! And C# is my fav programming language! :smile:

for (int i = 0; i < 5; i++)
    OnSpawnEnemy = delegate { Debug.Log(i); }

This code makes no sense, at least I don’t see any, but if you want to get 01234, you can write it like this:

for (int i = 0; i < 5; i++)
{
    int i2 = i;
    OnSpawnEnemy += delegate { Debug.Log(i2); };
}
OnSpawnEnemy(); // prints 0 1 2 3 4

The temporary local variable is necessary, otherwise you’ll get 55555 or maybe something else you don’t expect too see. If you wonder why, read about closures and what they close over.


If at some point you decide to subtract your delegates, be careful:

class Program
{
    static void Main(string[] args)
    {
        Action a = A;
        Action b = B;
        Action c = C;

        Action x = (a + b + c) - a - c;
        x(); // prints B
        Console.WriteLine();

        Action y = (a + b + c) - (a + c);
        y(); // still prints ABC, because ABC sequence doesn't contain AC
        Console.WriteLine();

        Console.ReadLine();
    }

    private static void A() { Console.Write('A'); }
    private static void B() { Console.Write('B'); }
    private static void C() { Console.Write('C'); }
}
5 Likes

@Stramit : Thanks for the infos ! There’s clearly a danger here … I should check that out now … :slight_smile:

@Alexzzzz : the code was just for quick explanation purpose :wink: And thanks for your tips too ! I didn’t grab that boolean logic yet, that’s great info.

So in the end, should I deduce that Virtual/Override are safer concerning memory and GC ?
Therefore better for an intensive function triggering ? (like state manager)

@Stramit :

Now I’m afraid :stuck_out_tongue:
If I understood correctly, you mention there that when a container (gameobject) is destroyed, the references in his components are not ? (assuming they’re not referenced anywhere else)
Is it like that ? For example I have let’s say a “system” gameObject, where I put a bunch of Texture2D references, all loaded with Resources.Load. If I destroy this System gameObject, those Texture2D references won’t be cleared ? :open_mouth:
Shouldn’t it be the case ?

Well the references will be GC’d so long as nothing else is referencing them. The thing is by adding delegates the delegate can reference the fields and they will not get GC’d.

1 Like

Ok thanks :slight_smile:

A brief example:

public class FooManager : MonoBehaviour
{
	public Action actions = null;

	public void DoActions()
	{
		actions();
	}

	// ...
}
public class Foo : MonoBehaviour
{
	private byte[] hugeAmountOfData = new byte[100000000];
	private FooManager manager;

	private void Start()
	{
		manager = (FooManager) FindObjectOfType(typeof (FooManager));
		manager.actions += DoSomethingUseful;
	}

	private void DoSomethingUseful()
	{
		//...
	}

	// ...

	private void OnDestroy()
	{
		manager.actions -= DoSomethingUseful; /* You need this, because 'actions' delegate
											  * still contains a reference to this Foo instance,
											  * which means the instance will always stay alive
											  * and won't be collected by the GC. */
	}
}
3 Likes

Ok. I understand the logic, but, shouldn’t a Destroy() (in an ideal world) turn every instance of it to null?
Like here, calling manager.actions() should ideally make a NullReferenceException ? (if we don’t substract to manager’s delegate)

var referenceToInstance = new GameObject("Lucky");
var secondReferenceToTheInstance = referenceToInstance;
var andAnotherOne = referenceToInstance;

DestroyImmediate(referenceToInstance); /* Releases some internal resources that
	the instance were using, but it doesn't destroy/erase/eliminate the instance
	* completely, only the garbage collector can do it. But at this moment the GC
	* still can't collect the object, because there are three references to it.
	* There's no any magical way that Destroy() could set all the variables to null,
	* they are still pointing at the halfdead object. */

Debug.Log(referenceToInstance == null); /* Prints 'true', because UnityEngine.Object
* overrides the comparison and returns 'true' if the object is marked as destroyed.
* It doesn't mean that the reference is actually null. */
Debug.Log(ReferenceEquals(referenceToInstance, null)); // Prints 'false' (that's the truth :)

referenceToInstance = null;
secondReferenceToTheInstance = null;
andAnotherOne = null;

/* Now there are no live references to the object and the GC is able to collect it. */

Debug.Log(ReferenceEquals(referenceToInstance, null)); // Prints 'true'
4 Likes

Gotta love C# :slight_smile:

I didn’t know about Action and Func. I’ve been writing my own delegate definitions here, and looks like I may have reinvented the wheel a few times, heh.

Cheers

1 Like

Ok thank you Alex, that makes sense now.
If we wanted Destroy to take full control of that nullification, there should be a “ref” keyword as object parameter I suppose.

When you do a += to register a delegate you must always add a -= to the same delegate otherwise the game will leak like hell.

By the way delegate are not that fast, they are slow actually. But indeed it is very powerful and useful for event management.

You made a example with Spawning enemies, but instead of using delegate, i prefere here to use an Interface (with a spawn function) and to implement decorator pattern to add different logic to the spawn.

Welcome to continuations/closures. :wink:

BTW JavaScript supports this and, while I haven’t used Java in 15 years, I would assume it does too though it might be hackish, I’m not really sure. In fact most languages support this sort of thing though it might take a bit of thinking-outside-the-box to get it done.

Thought someone would find them useful. C# started off with hideously verbose delegates and slowly made them more and more usable.

For those interested in finding out more about C#'s awesomeness C# in Depth is a great book. My list of everyday cool things are:

  • Extention Methods
  • Lambda’s
  • Linq
  • IEnumerator/IEnumerable
  • Named Optional paramaters. Oh, and Params.
  • Nullables
  • Generics

I don’t declare delegates often, but I do like mucking around with them on occasion:

delegate _ _();
_ _ = null; _ = () => _;

_()()()()()()()()()()()()()()()()()();
1 Like

Thanks for the link Cripple :wink:

Delegate are slow ? Meh, I’m confused, I read the exact opposite on Stackoverflow ? They were benchmarking Virtual/Override vs delegates, and results showed same perf ?
edit : here it is : c# - Performance of calling delegates vs methods - Stack Overflow
Most voted answer benchmarks delegates as faster than interfaces.