Delegates in C# - mariusz-tang/KTaNE-Module-Template GitHub Wiki

Although this guide assumes prior programming experience, delegates are something that you may still be unfamiliar with. Delegates are types that represent references to methods, and are often used for event handling. When modding, we often use delegates to run code in response to buttons being pressed, as seen in this code snippet:

button.OnInteract += delegate () { DoSomething(); return false; };

Here, button.OnInteract is the event handler which is called when the button, which is a KMSelectable, is interacted with, and we are subscribing to the event using the assignment operator +=. This means that, when button.OnInteract is called, the code in the DoSomething method will run, and then the delegate will return false. Any number of delegates can be assigned to an event handler, and they will all be called every time the event happens.

In this guide, I will use the following alternative syntax:

button.OnInteract += () => { DoSomething(); return false; };