0
Delegates.
Hello all. Can someone explain the usefulness of delegates in C#? Like examples for what they are good for? Thanks in advance.
2 Answers
+ 2
They can be used to call many methods at once. Specially useful for events.
Ex/
(syntax from Unity (mono)):
myButton.onClick.AddListener(
delegate{
callMethod1();
callMethod2();
}
);
On button press both methods are called.
It can also be used to attach any methods that are dependant on eachother.
Quoted from stackoverflow:
"Delegates are useful to offer to the user of your objects some ability to customize their behavior."
Some more examples here
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate
0
I use it for Unity also. Thanks