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 c
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 |
-------------------------------------------------------------------------|
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();
}
}
}