I'm playing around with events/delegates and I constantly get the following error:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll
Additional information: Exception has been thrown by the target of an invocation.
My code is as follows:
namespace Test
{
using System;
using System.Windows;
public partial class TestWindow : Window
{
public TestWindow()
{
this.InitializeComponent();
this.TestEvent(this, new EventArgs());
}
public delegate void TestDelegate(object sender, EventArgs e);
public event TestDelegate TestEvent;
}
}
Obviously, I have code in another location to open the TestWindow object:
TestWindow testWindow = new TestWindow();
testWindow.TestEvent += this.TestMethod;
And:
private void TestMethod(object sender, EventArgs e)
{
}
You are calling the event in the constructor, meaning during the window initialization, so the
TestEvent
is null at that time. Add a null check for theTestEvent
and call it in some method other than the constructor, checking if theTestEvent
has a subscriber assigned to, i.e., it is not null.Edit:
Here is a bit of code to demonstrate: