So I'm at the point of understanding events and delegates.
I overally understand the usage of delegates. The only thing that concerns me about delegates is whether a delegate can be configured to work with functions that are not related to events in any way... if yes, how do I write the logic for a delegate-defined function? (I guess such function doesn't really have much of a point to it, but it's good to know.)
As for events... I'm having a hard time understanding it. I get the idea that an event is a function that gets executed when something happens in the code. However, I don't get the process of creating an event. Partially.
For this question I'll use an answer by Gary Willoughby: https://stackoverflow.com/a/803528/1104766 It was posted on a question from which I tried to understand this whole subject.
What I didn't get in the example above:
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
First, how can you create an instance of a delegate, and pass it only 1 variable when it requires 2? There must be something I'm missing...
The second thing about this line is that the new ...()
instance is being added to the OnMaximum
function that resides in MyObject
which is an instance of MyClass
- what exactly is OnMaximum
if such thing can be done? It was never really defined too!
if(OnMaximum != null) {
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
As for this part, OnMaximum
is called but it's logic was never really defined anywhere in the code, so what could be the outcome? Obviously I'd guess it'd be the text "You've entered............." but my question is to be more specific, what really happens with the values the function/event receives?
I marked all of my questions in BOLD for clarity.
P.S, I know this question generally has been posted a few times.
Please note that this specific question refers to an answer written by another member and the questions asked here are specific to this example. That's why such answers can't really be found in google.
For the record though, I did search before I posted, and I did try to understand, but I guess examples are the best way for me to understand something especially when my knowledge of the English CS vocabulary is lacking.