I think I need to explain more why your approach is pointless. Your code is simply equivalent to this:
public class Class1
{
public Class1()
{
if (this.isClassLoaded == null) { Console.WriteLine("ClassLoaded null argument"); }
FirstHandler_EventHandler("10 points");
Console.WriteLine(isClassLoaded.ToString());
}
protected void FirstHandler_EventHandler(string message)
{
}
}
Are you getting the idea? The event instances are needed to handle some event by different users of the class independently. Those users add different handles to the invocation list of the event, and all those handlers are called by the method
Invoke
of the event instance. Handling the event in the class declaring the event is totally useless and means defeat of the purpose of events.
Another your problem is the idea that instantiation of the class object can be handled with an instance (non-static) event. Your event is public, so it implies the class still can have users which can handle the event. The problem is:
this event instance will never call any handlers (except your
FirstHandler_EventHandler
, which is pointless as I already explained before). Why? Just because the user code will be able to add a handler to this event after the instance of the class is already obtained. But in this case, a handler would be added too late, as the event instance is only invoked in the constructor. More generally,
invocation of any non-static (instance) events in a constructor is totally useless.
Also, handling such event as object creation (which you mistakenly call "loading") is useless in principle. When you have a fragment of code creating the object, this is your event. Just think about it.
And, just for a record: with static event instances, the situation is totally different. You can use similar technique to catch the event when every instance of some class is created. This may make some sense, because one part of code creates an instance, and some other parts get notification on this event. But you should understand that
using any static members is not thread-safe. To make such technique thread-safe, you could use thread synchronization primitives (such as lock), but the use of them depends on the threading scenario, so I would prefer not to discuss threading here. For example:
class MyClass {
public static System.EventHandler ClassLoaded;
public MyClass() {}
if (ClassLoaded != null)
ClassLoaded.Invoke(this, new EventArgs());
}
}
MyClass firstObject = new MyClass();
MyClass secondObject = new MyClass();
It may make certain sense because the event of creation of each of the instances (like those shown above) could be handled in one more mode
different places of code:
MyClass.ClassLoaded += (sender, eventArgs) => {
MyClass instance = (MyClass)sender;
instance.SomeMyClassMember
}
Are you getting the idea now?
—SA