How to know if a delegate has been assigned to an event????

  • Thread starter Thread starter Bob Rock
  • Start date Start date
B

Bob Rock

Hello,

is there a way to dynamically query if a callback delegate has been
tied to an event to avoid raising the event if none have been tied or
raise an exception if proper for the situation???
Thx.


Bob Rock
 
Bob Rock said:
is there a way to dynamically query if a callback delegate has been
tied to an event to avoid raising the event if none have been tied or
raise an exception if proper for the situation???

The normal way is:

if (myEventDelegate==null)
{
....
}

That's assuming the code which needs to find this out is within the
class declaring the event - you can't find out from outside.
 
Try this:
if (myEventDelegate != null)
{
myEventDelegate(...);
}

Delegate types represent references to methods with a particular signature and return type. They make it possible to treat methods as objects that can be assigned to variables and passed as parameters. As such they can be compared to null just as easily as any other reference.
 
You can get the delegates invocation list using GetInvocationList. The count
of objects in this array is the number of handlers tied to the event. The
order in which they are presented in this list is the order in which the
event will call them.

--
Bob Powell [MVP]
Visual C#, System.Drawing

The Image Transition Library wraps up and LED style instrumentation is
available in the June of Well Formed for C# or VB programmers
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

The GDI+ FAQ RSS feed: http://www.bobpowell.net/faqfeed.xml
Windows Forms Tips and Tricks RSS: http://www.bobpowell.net/tipstricks.xml
Bob's Blog: http://bobpowelldotnet.blogspot.com/atom.xml
 
Bob Powell said:
You can get the delegates invocation list using GetInvocationList. The count
of objects in this array is the number of handlers tied to the event. The
order in which they are presented in this list is the order in which the
event will call them.

Bob, thank you. Unfortunately doing myEvent.GetInvocationList().Length
causes an exception if the event has no delegated tied to it ... there
is no array in that case.

Jon controlling the null value on the event works perfectly well.


Bob Rock
 
Back
Top