views:

134

answers:

4

Hi there,

I am having a bit of trouble subscribing to an event I have created. The event itself is in its own class and I want to be able to subscribe to it from a separate class in a separate project. I am able to subscribe to it from the class in which it is created - but when I try to subscribe from a different class in a different project nothing happens.

Could someone give me a few pointers on how I can work through this at all? I have been all over Google trying to find a solution but to no avail :(.

+5  A: 

Here is a simple example of an event I have created and subscribed to:

using System;

class Program
{
    static void Main()
    {
     Foo foo = new Foo();
     foo.Fooing += () => Console.WriteLine("Foo foo'd");

     foo.PleaseRaiseFoo();
    }
}

class Foo
{
    public event Action Fooing;

    protected void OnFooing()
    {
     if (this.Fooing != null)
      this.Fooing();
    }

    public void PleaseRaiseFoo()
    {
     this.OnFooing();
    }
}

Hopefully this ought to be able to point you in the right direction. The main things to check in your code:

  • Is your event marked as public?
  • Do you ever raise the event? (e.g. this.Fooing())
Andrew Hare
A: 

Have you tried this?

MyInstanceOfMyClass.MyEvent += new EventHandler(MyDelegate);
protected void MyDelegate(object sender, EventArgs e) { ... }
Maxime
+1  A: 

I just tried your sample code with an EventHandler delegate instead of Action (since I couldn't find a non-generic Action delegate in the System namespace)

The code below works just as you'd expect: It outputs "Foo foo'd".

Maybe it's the Action delegate, though I find that somewhat weird.

class Program
{
    static void Main()
    {
        Foo foo = new Foo();
        foo.Fooing += (object o, EventArgs e) => Console.WriteLine("Foo foo'd");

        foo.PleaseRaiseFoo();
    }
}

class Foo
{
    public event EventHandler Fooing;

    protected void OnFooing()
    {
        if (this.Fooing != null)
            this.Fooing(null, null);
    }

    public void PleaseRaiseFoo()
    {
        this.OnFooing();
    }
}
Steffen
The sample code was posted by Andrew, not the OP. Andrews code should work as is.
Brandon
Oh my, I'm terribly sorry - didn't mean to steal the answer :-(
Steffen
A: 

You noted that your class is in a different project, can you see the event class (or any other class in that project)? Perhaps you haven't referenced your other project properly.

Nathan Koop