You are right that if you want to raise an event on the creation of an object then you need a static event. The event should be contained in the class itself, though, to adhere to the OOP encapsulation principle.
Also, it's not a great idea to fire events from constructors for various reasons that live in deep, dark caves in the CLR. The way around this is to only allow instances to be created from a factory method.
Something like this (picking up a couple of other points along the way):
c# code: // Derived from EventArgs class
class FooCreatedEventArgs : EventArgs
{
// Field marked readonly can only be set in constructor/initializer
private readonly Foo foo;
public FooCreatedEventArgs(Foo foo)
{
this.foo = foo;
}
public Foo Foo { get { return this.foo; } }
}
class Foo
{
// Use the generic EventHandler delegate rather than declaring your own
public static event EventHandler<FooCreatedEventArgs> Created;
// Event-raising method marked private, can't be called from other classes
private static void OnCreated(Foo foo)
{
// Thread-safe pattern for raising events
var handler = Created;
if (handler != null)
handler(null, new FooCreatedEventArgs(foo));
}
// Private constructor, prevents creating instances with new operator
// except from within this class
private Foo()
{
// All constructor code
// ...
}
// Factory method creates instances and fires event
public static Foo Create()
{
var foo = new Foo();
OnCreated(foo);
return foo;
}
}
class Program
{
static void Main(string[] args)
{
Foo.Created += HandleFooCreated;
var foo1 = Foo.Create();
}
static void HandleFooCreated(object sender, FooCreatedEventArgs e)
{
Console.WriteLine("A new Foo! Halloo!");
}
}
Any questions? |