I made this code in a class library named usedelegates:
namespace useofdelegates
{
public class Class1
{ //int i;
public delegate void mydelegate(object sender,EventArgs e);
public event mydelegate myevent;
public void fire()
{
EventArgs ee = new EventArgs();
myevent(this,ee);
}
}
}
Then in a windows form application, I intended to fire this event on the click of a button. The code in the form application is:
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
useofdelegates.Class1 ob;
private void button1_Click(object sender, EventArgs e)
{
// ob = new useofdelegates.Class1();
***ob.fire();***//give exception as object reference not set to an instance of an object.*/
}
private void Form1_Load(object sender, EventArgs e)
{
useofdelegates.Class1 ob = new useofdelegates.Class1();
ob.myevent+=new useofdelegates.Class1.mydelegate(ob_myevent);
// ob.fire();
}
public void ob_myevent(object sender, EventArgs e)
{
MessageBox.Show("hello hapiness");
}
}
}
This code on compiling throws an exception:
Object reference not set to an instance of an object.
but when I call ob.fire() in form_load(), it gives me the desired result without any exception. Why is this happening?