event and delegates

I wanted to know why use events and delegates when I can instead call functions normally?

Decoupling.

3 Likes

Lets say you have a class called ā€˜Button’. All it does is represent a simple button with text for a label and it can be clicked.

You add a button to your scene for the user to click. When the button is clicked, it calls a function called ā€œStartGameā€. And it loads the next scene. If you just call functions directly… it is now hardcoded to call ā€œStartGameā€.

Now, what if you add another button? And you label it ā€œExit Gameā€ and you want it to call a function called ā€œExitGameā€ which closes the application.

What do?

Copy the Button logic and make a ā€œExitGameButtonā€ that calls ā€œExitGameā€ when its clicked?

That’s… a bit overkill.

Rather instead how about the Button have an event called ā€˜Clicked’, and you can register a function with it to be called when the button gets clicked. Now you can reuse the same button code for multiple instances of buttons, but just like you can configure the label, you can also configure what function gets called.

…

this is called ā€˜decoupling’.

1 Like

More generally:

Why would you use variables like int x = 42 when you could just use the literal 42 everywhere you might have used x?

The answer is that variables give you generality. You can write block of code that can handle many different possible numbers, instead of only being able to handle 42. That way, if you discover tomorrow that you also need to handle 43, you don’t need to write new code for it.

You can even have the value of x change over the course of the program, so it means different things at different times.

Events and delegates are basically variables for functions. They allow you to write one block of code that can interact with a variety of different functions, instead of only with a single hard-coded function.

Is it all a performance thing?

Nothing in my post suggested it was a performance thing.

It’s a reduction of the amount of code you have to write. And instead designing systems abstractly. A button doesn’t do 1 thing (call 1 function), it can do many things, depending the situation.

The exit game button on the other hand does 1 thing… but that’s a specific configured instance of A button.

It lets you treat a method itself as a variable. Very useful in certain situations.

I think, more important for everyone else to know is what issues you have or are facing when you use delegates and events to warrant this question at all.

delegates and events are so flexible in usage its hard to describe their advantages briefly. You’ll simply have to experience using them yourself in time.