tags:

views:

79

answers:

2

I use them for "communication" between different objects, as publisher and subscriber pattern.

Is some examples I see that sometimes event is declared as static and sometimes it's not:

public delegate void LogProgress(string str)
public static event LogProgress LogProgressEvent;


 if (LogProgressEvent != null)
                LogProgressEvent(tempString);

Why and when I need to use static?

+6  A: 

Static events are actually quite dangerous, and (fortunately) also quite rare. As with anything static, you would use it when it applies to the type generally, not any specific instance. And even then, you might see it on a singleton instance rather than as a static event.

The danger is that it is ludicrously easy to forget to unsubscribe, and end up keeping masses of objects alive forever; contrast to most instance-based events - usually, the instance will go out-of-scope eventually, making the delegates collectable (a delegate instance will keep a target instance alive).

Marc Gravell
So I should always create NONE static events, right? but If I do so, this will require me to create an instance of the class that calls the event like:DataClass data = new DataClass();data.LogProgressEvent += new data.LogProgress(UpdateTextBox);
markiz
Just be careful. If you only subscribe to it from a few key places (infrastructure, etc) you should be OK; but avoid subscribing from your data entities (`Person`, `Order`, etc)
Marc Gravell
but if I still use in "data entities" objects, won't the garbage collector clean the mess after this data entity object is gone?
markiz
No... the static even subscription will **prevent** it from being collected.
Marc Gravell
A: 

static applied to events is not different from applying static to any other C# field.

static events are available to callers at any time, even if no instance of the class exists. I guess if you want to raise events from a static method, static events will be useful

See implications of using static events in Marc's answer

P.K
I'd probably tend towards callback delegates as parameters, for the reasons given in my answer...
Marc Gravell
@Marc I agree with you
P.K