4

i created a class and when i create an employee object via form , i want to give a message;

this is my class, event and delegate

public delegate void ctorDel(); 

class Employee
{
    private int empID;
    private string empName;

    public event ctorDel myEvent;

    public Employee(int empID,string empName)
    {
        this.empID = empID;
        this.empName = empName;

        **if (myEvent != null)
        {
            myEvent();
        }**
    }

and in form

  int id = Convert.ToInt16(textBox1.Text);
            string name = textBox2.Text;

            Employee emp = new Employee(id, name);
            emp.myEvent += new ctorDel(showMessage);

and function

 public void showMessage()
        {
            MessageBox.Show("An employee is created");
        }
3
  • 3
    What is your question then? Where are you having problems?
    – Oded
    Nov 23, 2011 at 14:36
  • myEvent will never be fired, because it's not set anywhere.
    – Krzysztof
    Nov 23, 2011 at 14:37
  • Nobody can attach to the event, so that makes no sense.
    – Hubi
    Nov 23, 2011 at 14:38

6 Answers 6

8

What is it you're trying to accomplish? The reason what you've tried doesn't work is because you're attaching your delegate after the ctor. Once you've called "new Employee" the event is long since fired.

If you really need such an event, create a factory class:

public delegate void EmpCreated();
public EmployeeFactory {
  public event EmpCreated myEvent;
  public Employee Create(int empId, string empName){
    var result = new Employee(empId, empName);
    if(myEvent != null) myEvent();
    return result;
  }
}

Subscribe to the event on the factory class and you'll get the event.

1
  • can i do this in employee constructor ? Nov 23, 2011 at 14:44
7

You're attaching the event after the constructor has already run.

2

It doesn't make sense to raise an instance event in the constructor, because since the initialization of the instance is not yet complete, there can't be any handler attached to the event...

However, you could create a static event:

public static event ctorDel myEvent;

...

Employee.myEvent += new ctorDel(showMessage);

(but don't subscribe to the event every time you create an Employee, or the handler will be invoked as many times as there are instances...)

2

Solution

Here's a generic approach to your problem

public class EventFactory
{
    public U Create<U, V>(V constructorArgs)
    {
        var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
        OnCreated?.Invoke();
        return instance;
    }

    public delegate void CreatedEventHandler();
    public event CreatedEventHandler OnCreated;
}

You can then do

var ef = new EventFactory();
ef.OnCreated += myEventHandler; 
var instance = ef.Create<Employee>(employeeArgs);

.. Going further

It is possible to adjust my code to provide greater flexiblity when you need to pass event arguments or when the constructor is parameterless. I haven't tested it but it should look somewhere along the lines of

public class EventFactory<T>
{
    public U Create<U, V>(V constructorArgs, T eventArgs)
    {
        var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
        OnCreated?.Invoke(eventArgs);
        return instance;
    }

    public U Create<U>(T eventArgs)
    {
        return Create<U, object>(null, eventArgs);
    }

    public delegate void CreatedEventHandler(T args);
    public event CreatedEventHandler OnCreated;
}

public class EventFactory
{
    public U Create<U, V>(V constructorArgs)
    {
        var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
        OnCreated?.Invoke();
        return instance;
    }

    public U Create<U>() where U : new()
    {
        var instance = new U();
        OnCreated?.Invoke();
        return instance;
    }

    public delegate void CreatedEventHandler();
    public event CreatedEventHandler OnCreated;
}
0

You can pass the handler when creating the Employee:

private Employee(ctorDel construcEvent)
{
    if (construcEvent != null)
        this.myEvent += construcEvent;
}

public Employee(int empID,string empName, ctorDel construcEvent)
    : this(construcEvent)
{
    this.empID = empID;
    this.empName = empName;

    if (myEvent != null)
    {
        myEvent();
    }
}

And then:

Employee emp = new Employee(id, name, new ctorDel(showMessage));
0

By the time you subscribe for this event the instance is already constructed. I would recommend using Factory pattern to hide the constructor.

class EmployeeFactory
{
     public Employee Create(int id, string name)
     {
         Employee instance = new Employee(id, name);

         var handler = EmployeeCreated;
         if (handler != null)
         {
              EmployeeEventArgs e = new EmployeeEventArgs(instance);
              handler(e);    
         }

         return instance;
     }

     public event EventHandler<EmployeeEventArgs>  EmployeeCreated;
}

Event subscription:

  factory.EmployeeCreated += MyHandler;

Instance construction:

  var emp = factory.Create(id, name);  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.