C# Is it possible to use the weak event pattern with a static class?

424 views Asked by At

I have a static class I was using because I didn't like the idea of passing around a gigantic settings file, but then I wished to be able to have instances subscribe to static events on the static class.

I was looking into using the PropertyChangedEventManager's AddListener method, but it needs an instance to add.

is this even possible? i'm on .net 4.0, in case it matters.

1

There are 1 answers

8
Matt On

You can have a static event and have multiple instances subscribe to it. You'll just have to keep in mind all instances that are wired will get notified of event and their implementation invoked. This also can have issues in memory management, your instances won't go out of scope and get GC'd until they unwire themselves from the event.

Heres an example script to show:

delegate void Pop();
static event Pop PopEvent;

void Main()
{
    var t1= new Thing("firstone");
    var t2= new Thing("secondOne");

    //fire event
    PopEvent();
}

public class Thing
{
    public Thing(string name)
    {
        this.name = name;
        PopEvent += this.popHandler;
    }

    private string name="";

    public void popHandler()
    {
        Console.WriteLine("Event handled in {0}",this.name);
    }

}

Output:

Event handled in firstone Event handled in secondOne