views:

229

answers:

2
public sealed class FtpManager
{
    public event EventHandler LoggingIn = delegate { };
    private void OnLoggingIn(object sender, EventArgs e)
    {
        var handler = LoggingIn;
        handler(sender, e);
    }
// ...
}

In the above code, I have initialized LoggingIn event handler with an empty delegate.

Will that affect memory space used in any way? Especially when there are hundreds or thousands of events declared such way?

+3  A: 

Scratch the previous answer (kept below for posterity). It depends on the implementation of the compiler, but under the current MS C# 3.0 compiler, this actually only creates a single instance which is reused for every instance. It's able to do that because delegates are immutable and that delegate doesn't require any information from the instance.

I don't know whether this was the case with C# 2.0 though. You can decompile your code and see whether the IL actually uses a cached field or not. Using the answer below is a safe way to guarantee you'll only create one instance though.

Original answer:

Yes, it creates an instance of a delegate. That will take some memory. You could reduce that though:

public static class EventHandlers
{
    public static readonly EventHandler Empty = delegate {};
}

public sealed class FtpManager
{
    public event EventHandler LoggingIn = EventHandlers.Empty;
}

At that point there'll just be the one instance, and you can refer to it from anywhere. The downside is that other classes could then unsubscribe using the same handler. If you trust the rest of your codebase not to do that, this is probably the best bet from a memory point of view.

Jon Skeet
Wow, I think a part of the reason my app is running wild with high memory usage could be because I have been declaring events with an empty delegate...; thanks again, Jon
Sung Meister
@Sung: I've completely changed my answer. Will go back and edit to put the previous version too though!
Jon Skeet
@Sung: Okay, it's now significantly more complete. You should be able to check whether or not this is your problem by decompiling your app. Reflector is good for this, but you'll need to look at the IL to be sure about what's really happening.
Jon Skeet
A: 

The alternative to doing this is checking LoggingIn for nullity every time you want to raise it. That's liable to be more memory intensive than calling an empty delegate.

Jekke
Did you run any tests to support this, or is just an assumption?
Dan C.
No. I just pointed out a limiting factor. If you wanted tests, you could have written them just as easily as anyone else.
Jekke