help with events to make this little code from patterns & practices work  
Author Message
R.Tutus





PostPosted: Visual C# General, help with events to make this little code from patterns & practices work Top

Hi I saw this code in patterns & practices for defining events for business entity:

My question is right at the buttom.

// Define a common event class for all business entity events
public class EntityEventArgs : EventArgs
{
  // Define event members, to provide information about the event
}

// Define a delegate specifying the signature for business entity-related
events
public delegate void EntityEventHandler(Object source, EntityEventArgs e);

// Define a custom Entity class that raises events when the business entity
state changes
public class OrderEntity
{
  // Define 'before' and 'after' events for business entity state changes
  public event EntityEventHandler BeforeChange, AfterChange;

  // Private fields, to hold the business entity's state
  private int orderID;

// Public properties, to expose the business entity's state
  public int OrderID
  {
    get { return orderID; }
    set
    {
      BeforeChange(this, new EntityEventArgs());   // Raise a 'before' event
      orderID = value;
      AfterChange(this, new EntityEventArgs());    // Raise an 'after' event
    }
  }

What I don t know is how to put the method that I want to invoke whenever the AfterChange event is raized. Let s say if I want the method myMethod to be called whenever the event AfterChange is raized, where do I put such method and how do i put it

Thanks for your help.




Visual C#10  
 
 
boban.s





PostPosted: Visual C# General, help with events to make this little code from patterns & practices work Top

After creating instance of OrderEntry, add handlers for two events:

OrderEntry orderEntry = new OrderEntry(..);
orderEntry.BeforeChange += new EntityEventHandler(OnBeforeChange);
orderEntry.AfterChange += new EntityEventHandler(OnAfterChange);

...

private void OnBeforeChange(object sender, EntityEventArgs e)
{
...
}

private void OnAfterChange(object sender, EntityEventArgs e)
{
...
}



 
 
R.Tutus





PostPosted: Visual C# General, help with events to make this little code from patterns & practices work Top

That makes sense. I also got another answer that there is no sense to create the method for handling the BeforeChange and AfterChange events inside OrderEntry class, we only create the method outside the class as you mentionned, right

By the method to handle the events I mean this part of youe code:

private void OnBeforeChange(object sender, EntityEventArgs e)
{
...
}

I don t know what you call this last method. is it called event handler or something else

Thanks a lot.



 
 
boban.s





PostPosted: Visual C# General, help with events to make this little code from patterns & practices work Top

They are methods. But because are used to be called when event are raised, mostly are named Event Handlers.