Understanding Delegate Point in C #

I read honestly, and I am at a stage where I am beginning to understand what they are doing, but I am at a loss when it comes to why and where I will use them. In each example, I saw that a repeating definition looks like a method pointer, and you can use it instead of calling a method, which seems to be useful when the developer does not know which method to call or select a method based on state or state.

Here I'm struggling a bit, why can't I just have an if statement or a switch statement and then call the method directly based on the result? What's wrong with calling a method directly from an object instance? In my opinion, the delegate offers a better way to do this, but I can’t understand what is better about it, from my point of view, this is just a round-robin way to achieve the same thing as the if statement when you decide which method to call.

I am perplexed and chatting a little now, any help on this issue would be very appreciated!

+4
source share
2 answers

why can't I just have an if statement or a switch statement and then call the method directly based on the result?

It would be nice if you had 2 or 3 different branches and methods. Now imagine that you have dozens or hundreds of methods that can be potentially called depending on the situation. I would not want anyone to write this if statement.

Imagine a character in a game has 100 different potential abilities. Each ability can have its own method for execution. Depending on what abilities the player has, you can simply drop these methods into the list for this symbol using delegates. Now his fully customizable abilities and the player’s abilities are not written in the code, and they can easily or simply be picked up or lost during the game, and there can be thousands of abilities, not to mention the number of potential combinations.

+3
source

Think of it this way. According to the SOLID OOD principle (for example), each object must be responsible for one part of the functionality. Using this principle, we can assume that:

Classes are responsible for working with custom objects, structs with are data sets, methods are responsible for actions, events are responsible for signaling that something is happening, and delegates are responsible for the corresponding action on these events that should happen.

Events and methods are “occupied” with their own part of functionality and therefore cannot process the events themselves and bear responsibility for the methods. That's why we need delegates ...

+2
source

All Articles