Search code examples
c#eventssyntaxlambdaexpression

Add event handler during object initialization


I need to pass a instance (which will be created in this very moment) of a certain type to a method. This type offers several events which I'd like to subscribe to too, so my code looks like this:

var instance = new Instance();
instance.OnEvent1 += (sender, args) => {
    DoThis();
    DoThat();
}
instance.OnEvent2 += (sender, args) => DoThisToo();
instance.OnEvent3...
MyMethod(instance);

Now, is it possible to add the handlers during initialization? So I can write something like this:

MyMethod((MyType)instance => {
    instance.OnEvent1 += (sender, args) => {
        DoThis();
        DoThat();
    }
    instance.OnEvent2...
});

This is, of course only desired because of cosmetic reasons. I like my code small & readable.


Solution

  • This is not possible right now but according to Roslyn it is planned and might be available in the future.

    --------------------------------------------------------------------------
    | Feature            | Example                                |   C#     |
    -------------------------------------------------------------------------|
    | Event initializers |  new Customer { Notify += MyHandler }; | Planned  |
    -------------------------------------------------------------------------|