When you declare an event using the event
keyword, you are really declaring two methods, add
and remove
. Think of it like when you declare a property: under the covers, you are really declaring a set
and a get
method. Events are no different; you can actually override add
and remove
in code, with a custom event accesssor.
So when you call
MyClass.MyEvent += MyEventHandler;
you are really calling
MyClass.MyEvent.add(MyEventHandler); //not real code
Naturally, the static constructor has to be run whenever any method is accessed, to ensure the static state of the class is correct. It's a feature. So to defer execution of the static constructor while adding to the event is not possible, I'm afraid.
If you want some initialization to run later, extract it to a separate method and call it separately, or load it lazily, as in my example. Another approach would be to assign the handler lazily, as taquion suggests in his answer. I only prefer my answer because it's a common pattern, and I'd like other engineers to understand what is going on in my code, especially if it is critical for your application that the initialization logic execute at a specific time.
static public class MyClass
{
static bool _initialized = false;
static MyClass()
{
Console.WriteLine("Test.ctor called");
}
static void Initialize()
{
Console.WriteLine("Test.Initialize called");
_initialized = true;
}
static public event EventHandler MyEvent;
static public void RaiseMyEvent()
{
if (!_initialized) Initialize();
if (MyEvent != null) MyEvent(typeof(MyClass), new EventArgs());
}
}