I am new in c# development. I just trying to study the delegate feature. Based on the articles and notes I read about delegates, I tried to write a sample code to implement delegate based on what I understood from those notes and articles.
But I am getting an error while running the sample
“Object reference not set to an instance of an object.”
What is the problem here ?. or Did I implemented the delegate in correct way ? or Is my concept about delegate is wrong ?..
Please help. Thanks in advance.
I posted my code below.
default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
TestClass myObject = new TestClass();
protected void Page_Load(object sender, EventArgs e)
{
myObject.MyDelegateEvent += new TestClass.MyDelegate(myObject_MyDelegateEvent);
}
void myObject_MyDelegateEvent(object sender, EventArgs e)
{
Console.WriteLine("Delegate event called");
}
}
TestClass
public class TestClass
{
public delegate void MyDelegate(object sender, EventArgs e);
public event MyDelegate MyDelegateEvent;
public TestClass()
{
MyDelegateEvent(this, null); // Here getting error "Object reference not set to an instance of an object."
}
}
What you are trying is: raising the event in the constructor itself, i.e. at the time when there is no subscriber for your event hence MyDelegateEvent is null.
Best option is to null check before raising the event