Events a la C# 3.0

The new language features makes it possible to minimize much of that nasty boiler plate code. With these helpers:

delegate void EventHandler<T>(object sender, T e); 

class EventArgs<T> : EventArgs {  
    readonly T _args; 
    public EventArgs(T args) { 
        _args = args; 
    } 
    public T Args { 
        get { return _args; } 
    } 
} 

static class EventExtensions {  
    public static void OnEvent<T>( 
            this object sender, 
            EventHandler<T> handler, T e) { 
        if (handler != null) 
            handler(sender, e); 
    } 
}

I can raise thread safe events with a generic typed event argument as simple as this:

class MyClass  
{ 
    public event EventHandler<Point> Click; 

    : // some method body 
    this.OnEvent(Click, new Point(4,2)); 
    : 
}

I currently find much inspiration in functional programming and the F# project.

Google
m@kli.dk @klinkby RSS feed  GitHub