Fabian
Fabian

Reputation: 63

C# Reflection: How to invoke a EventInfo?

how do i invoke the event behind a EventInfo ? I tried the following but "GetRaiseMethod" is always "null":

MethodInfo eventRaiseMethod = eventInfos[i].GetRaiseMethod();
eventRaiseMethod.Invoke(this, arrayOfPropertyChangedArgs);

Thank you :)

Update: Seems thats a bug in C# ???

EventInfo.GetRaiseMethod() always null

Upvotes: 2

Views: 2449

Answers (1)

Evk
Evk

Reputation: 101473

"Invoking" event only makes sense if event is implemented without overriding add\remove:

class Test {
    public event Action TestEvent;

    void Invoke() {
        // fine
        TestEvent();
    }
}

However, concept of invoking for event with custom add\remove does not make sense:

class Test {
    public event Action TestEvent
    {
        add { }
        remove { }
    }

    void Invoke() {
        // does not compile, invoke what?
        TestEvent();
    }
}

So event invocation is just syntax sugar of calling underlying compiler-generated delegate field, for events with "default" implementation.

Knowing that, you can search for that field and invoke it. This is a private field with the same name as event:

class Program {
    static void Main(string[] args) {
        var test = new Test();
        test.TestEvent += OnTest;            
        var backingField = typeof(Test).GetField("TestEvent", BindingFlags.Instance | BindingFlags.NonPublic);
        var delegateInstance = (Action)backingField.GetValue(test);
        delegateInstance();            
    }

    private static void OnTest() {
        Console.WriteLine("Event invoked");
    }
}

class Test {
    public event Action TestEvent;
}

That said, compilers of some .NET languages might generate "Raise" method for autoimplemented event. If that is the case - GetRaiseMethod will return such method. C# compiler doesn't do that though. So if you want to be safe - you might first call GetRaiseEvent and if it returns null - fallback to field approach. Of course you should expect field to be null also (since not all events are invocable as described above - there is not requirement for such field to exist).

Upvotes: 3

Related Questions