Yanshof
Yanshof

Reputation: 9926

How are "Event" objects implemented in .NET?

I just want to be sure that i understanding this ...

The 'Event' in .net is just a collection of delegates - and when some class want to get the 'Event' it use the '+' operator with the method that the delegate will point on ( kind of observer )

So, if the event is occurs => some pointer will walk on the collection and will call the method that was define in the event registration.

Am i right with this description ? Is it possible to see the Microsoft .net implementation of the 'Event' object somehow ?

Upvotes: 3

Views: 147

Answers (3)

JKhuang
JKhuang

Reputation: 1553

I consider that Event encapsulates delegates, just like the relative of properties and fields.

Upvotes: 1

Kendall Frey
Kendall Frey

Reputation: 44336

An event is actually a single delegate. Delegates actually support multiple callbacks. It's not an event thing.

Events can be used a lot like properties. Whereas properties have a get/set, events have an add/remove (though this is usually automatically implemented).

private EventHandler<EventArgs> myEvent;

public event EventHandler<EventArgs> MyEvent
{
    add
    {
        myEvent = (EventHandler<EventArgs>)Delegate.Combine(myEvent, value);
    }
    remove
    {
        myEvent = (EventHandler<EventArgs>)Delegate.Remove(myEvent, value);
    }
}

When an event is fired, basically the delegate is called. There isn't too much magic there.

I hope this helps. I don't think you will find the implementation for calling an event, as that is built into the CLR. It was mentioned that you could look at the Mono source.

Upvotes: 3

svick
svick

Reputation: 244837

There is no Event object in .Net. Events in .Net are all based around MulticastDelegates (and every delegate in .Net is a MulticastDelegate).

If you have two delegates of the same type, you can combine them using the + operators, that's not event-specific.

The way MulticastDelegate is implemented is that it has an invocation list that contains the simple delegates that will be invoked if you invoke this delegate. You can look at it by calling GetInvocationList() on that delegate.

And you could try looking at the implementation of MulticastDelegate, or, say, EventHandler in a decompiler like Reflector, but you won't see much there, it's all implemented directly in the Framework.

If you want to look at the source code of the Framework where code that deals with invoking delegates lives, you could try SSCLI, or you could try looking at the source code of mono (but that won't show you the MS implementation).

Upvotes: 5

Related Questions