Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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  |
-------------------------------------------------------------------------|

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...