[C#.NET] Delegates + Events...help me understand them

Soldato
Joined
12 Jun 2005
Posts
5,361
Hi there,

What I am doing at the moment is I am creating a class which will eventually go into a dll which can be included in other peoples projects.

Within that class I have some events which are triggered so that the application that had this library linked can update and do whatever it wants with the information.

The class is NOT static.

So here is the code I am using and it works:

Code:
public delegate void LogUpdateEvent(LogMessage Message);
public event LogUpdateEvent LogUpdated = new LogUpdateEvent(logstuff);

public static void logstuff(LogMessage hey)
{}

and then for my main program to handle that event i simply use this:

Code:
mvBrab.LogUpdated += new class.class.LogUpdateEvent(mvBrab_LogUpdated);

This works fine and it handles the events fine.

My main question is, do I have to have the static "logstuff" void in the class, because it is sitting there doing nothing? If so how do I do this? If not, why not?

Thanks.
 
Last edited:
Why did you put logstuff there in the first place? Like you said, it's doing nothing and isn't needed.

The only purpose it serves is to prevent an exception from being thrown if the event is raised without any (other) handlers, but you should instead do this by checking it for null before raising it, e.g.:

Code:
if (LogUpdated != null)
{
    LogUpdated(message);
}

Also, it's good practice to use the generic System.EventHandler<T> delegate for events rather than defining your own. Define a class to use with it that derives from System.EventArgs. For example:

Code:
public class LogEventArgs : EventArgs
{
    private LogMessage m_Message
    
    public LogMessage Message
    {
        get
        {
            return m_Message;
        }
        set
        {
            m_Message = value;
        }
    }
    
    public LogEventArgs(LogMessage message)
    {
        m_Message = message;
    }
}

Code:
public class Foo
{
    public event EventHandler<LogEventArgs> LogUpdated;
    
    public void Bar()
    {
        // Log some event.
        if (LogUpdated != null)
        {
            LogMessage message = new LogMessage(); // Create your LogMessage however you need to.
            LogUpdated(this, new LogEventArgs(message));
        }
    }
}
 
Last edited:
Back
Top Bottom