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");
}
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:
Subscribe to the event on the factory class and you’ll get the event.