all groups > dotnet clr > november 2007 >
You're in the

dotnet clr

group:

Is it possbile to enumerate Methods by Event?


Is it possbile to enumerate Methods by Event? athos.jingle@gmail.com
11/23/2007 10:29:14 AM
dotnet clr:
To attach a method to an event, we can use EventInfo.AddEventHandler.

After attached, given an event's name, is it possible to retrieve all
methods attached to it?

Re: Is it possbile to enumerate Methods by Event? athos.jingle@gmail.com
11/23/2007 12:36:08 PM
[quoted text, click to view]

OK I'm just curious...
Yeah I could not find a way to track, but, it should be somewhere in
the memory, right? Existing as a linked list, or inside an internal
Class... Unfortunately I don't know CIL (MSIL), and reflector stops at
the mysterious abstract Method "abstract MethodInfo GetAddMethod":

[DebuggerHidden, DebuggerStepThrough]
public void AddEventHandler(object target, Delegate handler)
{
MethodInfo addMethod = this.GetAddMethod();
if (addMethod == null)
{
throw new
InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
}
addMethod.Invoke(target, new object[] { handler });
}

public MethodInfo GetAddMethod()
{
return this.GetAddMethod(false);
}

Re: Is it possbile to enumerate Methods by Event? Jon Skeet [C# MVP]
11/23/2007 7:15:00 PM
[quoted text, click to view]

No. An event is really just a pair of methods, add and remove. Although
*usually* there's a delegate variable backing it, the add/remove can do
anything they want, and there's no part of an event which is a "fetch".

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Re: Is it possbile to enumerate Methods by Event? Jon Skeet [C# MVP]
11/23/2007 8:46:23 PM
[quoted text, click to view]

Usually, but not necessarily. For instance, you *could* write an event
that did nothing with the event handlers that you added:

public event EventHandler Foo
{
add {}
remove {}
}

Or here's an oddity - it adds to one delegate variable or another,
depending on the time of day (and removes from both):

EventHandler foo1;
EventHandler foo2;

public event EventHandler Foo
{
add
{
if (DateTime.Now.Hour >= 12)
{
foo1 += value;
}
else
{
foo2 += value;
}
}

remove
{
foo1 -= value;
foo2 -= value;
}
}

I'm not saying it's *sensible* (and in particular the removal side is
nasty) but it's valid code as far as C# and the CLR are concerned.

[quoted text, click to view]

It's not mysterious - it finds which method is called when you add an
event handler.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button