1
Answer

Class with Event, finaly more work than...

axel stein

axel stein

11y
880
1
Hi, this Axel nice to meet you guys.

I'm carring about events, during the last weeks.
Now after I can see how its work,  I woundering, what do I win by using of them?

Obviously at last I have to call my event, like this example
[code]
public int myProp
        {
            get { return _myProp; }
            set
            {
                if (value >= 0)
                    _myProp = value;
                else                 
                MeinEvent(this);     // call my_Event          
            }
        }
[/code]
So, it seems to me, its the same as I would call here any method?
Futhermore, to use my Event, I have to make my class ready.
myClass.MeinEvent += myEvent_Method;
And there has to be those Method "myEvent_Method"

Or is there anything I have not pass at yet?

greetings axel





Answers (1)
0
Vulpes

Vulpes

NA 98.3k 1.5m 11y
The main purpose of events (as implemented in .NET) is to prevent the subscribers from interfering with each other or with the event itself.

The only way a subscriber can subscribe, or unsubscribe, to an event is by using C#'s special += or -= operators. Subscribers do not know about other subscribers and cannot therefore interfere with them.

Moreover, code outside the broadcaster (i.e. the type which contains the event) is not able to access the event at all apart from via the += and -= operators or via any public method which the broadcaster may provide to indirectly fire or otherwise manipulate the event.

None of this is possible using 'ordinary' delegates (events are just a special type of delegate) which need to be public for subscribers to be able to subscribe to them in the first place. The subscriber therefore has direct access to the delegate and can view or manipulate its invocation list.