2

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 :(.

Svante
  • 50,694
  • 11
  • 78
  • 122

4 Answers4

6

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
  • 344,730
  • 71
  • 640
  • 635
1

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
  • 13,648
  • 7
  • 57
  • 67
0

Have you tried this?

MyInstanceOfMyClass.MyEvent += new EventHandler(MyDelegate);
protected void MyDelegate(object sender, EventArgs e) { ... }
maxbeaudoin
  • 6,546
  • 5
  • 38
  • 53
0

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
  • 24,803
  • 25
  • 90
  • 125