Delegates: How to check for target methods

  • Thread starter Thread starter Einar Høst
  • Start date Start date
E

Einar Høst

Hi,

I'm using delegates to show progress when performing certain tasks. However,
I'd like to check to see that there actually is a method available for the
delegate to call. What's the correct way of doing that? Looking at the
documentation for delegates, I've come up with:

if (MyEvent.Target != null)
{
MyEvent(this, new MyEventArgs());
}

Still, this would be correct for instance methods only, right? Would this be
better?

if (MyEvent.Method != null)
{
MyEvent(this, new MyEventArgs());
}

Thanks,
Einar.
 
Einar Høst said:
I'm using delegates to show progress when performing certain tasks. However,
I'd like to check to see that there actually is a method available for the
delegate to call. What's the correct way of doing that? Looking at the
documentation for delegates, I've come up with:

if (MyEvent.Target != null)
{
MyEvent(this, new MyEventArgs());
}

Still, this would be correct for instance methods only, right? Would thisbe
better?

if (MyEvent.Method != null)
{
MyEvent(this, new MyEventArgs());
}

Could you give an example of how you'd construct a delegate which
*didn't* have a method to call?
 
Einar,
However,
I'd like to check to see that there actually is a method available for the
delegate to call.

As long as the delegate isn't a null reference there is at least one
method to call, so you just have to do

MyEventHandler h = MyEvent;
if ( h != null )
h(this, new MyEventArgs());



Mattias
 
Einar Høst said:
Hi,

I'm using delegates to show progress when performing certain tasks. However,
I'd like to check to see that there actually is a method available for the
delegate to call. What's the correct way of doing that? Looking at the
documentation for delegates, I've come up with:

if (MyEvent.Target != null)
{
MyEvent(this, new MyEventArgs());
}

Still, this would be correct for instance methods only, right? Would this be
better?

if (MyEvent.Method != null)
{
MyEvent(this, new MyEventArgs());
}

Thanks,
Einar.

You should simply check if the delegate variable is null. An example:

[...]
private delegate void MyEventDelegate();

private MyEventDelegate myEvent;

private void button2_Click(object sender, System.EventArgs e) {
if (myEvent != null) {
myEvent();
} else {
Console.WriteLine("Empty Delegate. Adding methods");
myEvent += new MyEventDelegate(MyStaticMethod);
myEvent += new MyEventDelegate(MyInstanceMethod);
}
}

private static void MyStaticMethod() {
Console.WriteLine("Hello from MyStaticMethod()");
}

private void MyInstanceMethod() {
Console.WriteLine("Hello from MyInstanceMethod()");
}
[...]
 
Hi, thanks for responses, I believe 'if (MyEvent != null)' does the trick.
Obviously, I'm new to the whole delegate thing, so my understanding of it is
a bit muddled.

- Einar
 
Back
Top