Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate event issue

Tags:

c#

delegates

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."

    }

}
like image 419
Arun Avatar asked Mar 16 '26 06:03

Arun


2 Answers

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

//Check for not null
if(MyDelegateEvent != null)
{
    MyDelegateEvent(this, null);
}
like image 186
Maheep Avatar answered Mar 17 '26 18:03

Maheep


Always test for null before raising the event:

if (this.MyDelegateEvent != null)
{
     // Raises the event here
}

If no handler is attached to your event when it is raised (which is the case here as it's raised in the constructor), a null reference exception can be thrown.

EDIT: For the sake of completeness, when no event argument is used, you should use EventArgs.Empty instead of null:

if (this.MyDelegateEvent != null)
{
    this.MyDelegateEvent(this, EventArgs.Empty);
}

Also, there is a EventHandler delegate that can be used when you do not specify any event argument. This is useful as you don't have to write your own each time.

like image 22
ken2k Avatar answered Mar 17 '26 19:03

ken2k