Add event handler during object initialization
Asked Answered
C

3

2

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.

Cady answered 25/7, 2014 at 8:45 Comment(3)
That doesn't look like it's "during initialization" - that looks like it's "as part of the method call". Did you actually mean you want to do it as var instance = new Instance { OnEvent1 += ... }? If so, the answer is that you'll be able to do it in C# 6...Defective
@JonSkeet Great news! Can't the lambda expression parameter be considered as initialization (of an anonymous type)?Cady
Not really... it's just a way of providing a method. That's not initialization in itself.Defective
P
5

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  |
-------------------------------------------------------------------------|
Presently answered 25/7, 2014 at 8:49 Comment(3)
Really looking forward to it. Thanks!Cady
Note that this answers what I suspect the OP really wants, but does not match what is specified in the question - which is adding event handlers in a lambda expression. That's already supported. I suspect the OP is a bit confused between object initializers and lambda expressions.Defective
If you're keen to see this feature, you can vote for it on GitHub here: github.com/dotnet/csharplang/issues/307Limelight
S
0

I can advise you next trick in case if source code available: add public property with type of you event that take incoming value on set and attach this handler to event you need

For example:

namespace TrickAddEventHandlerInObjectInitializer
{
class A
{
    public EventHandler AddHandlerToEventByAssignMe
    {
        set { Event += value; }
    }

    public event EventHandler Event;

    public void DoSmthAndInvoke()
    {
        Event?.Invoke(this, new EventArgs());
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new A
        {
            AddHandlerToEventByAssignMe = A_Event
        };

        a.DoSmthAndInvoke();
    }

    private static void A_Event(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}
}
Synopsis answered 23/6, 2016 at 14:26 Comment(1)
what is your advise? Please add more explanation on how you try to address OP's issueSubmerged
B
0

There are times when it makes sense, and it is helpful, to set event handlers in your initializing expression. Jon Skeet's comment suggests that this is the question being asked. As the hoped for capability in C#6 did not happen, an alternative is

            var instance =
                ((Func<Instance>)(() =>
                {
                    var p = new Instance();
                    p.OnEvent1 += (sender, args) => { DoThis(); DoThat(); };
                    return p;
                }))();

which is useful in settings such as initializing background workers. The limitation here is that the event handler cannot be a non-static method, which keeps this approach from being useful when setting default backing properties.

Barefoot answered 21/12, 2023 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.