CodingC#- Custom Events

 

Press Ctrl+Enter to quickly submit your post
Quick Reply  
 
 
  
 From:  THERE IS NO GOD BUT (RENDLE)  
 To:  Monsoir (PILOTDAN)      
35958.4 In reply to 35958.2 
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?

Happy now?

0/0
 Reply   Quote More 

 From:  Monsoir (PILOTDAN)   
 To:  ALL
35958.5 
Excellent stuff, both - thank you very much!
0/0
 Reply   Quote More 

Reply to All    
 

1–5

Rate my interest:

Adjust text size : Smaller 10 Larger

Beehive Forum 1.5.2 |  FAQ |  Docs |  Support |  Donate! ©2002 - 2024 Project Beehive Forum

Forum Stats