1

I'm using delegates in my c# windows forms application project.Using that I'm trying to remove items in a list box. I'm getting this null pointer exception and can somebody suggest a way to avoid that?

Delegate

public delegate void OrderEventDelegate (Object sender, OrderEventArgs args);

OrderEventArgs class

public class OrderEventArgs
{
    private String message;

    public String Message
    {
        get { return message; }
        set { message = value; }
    }

    private int tableNo;

    public int TableNo
    {
        get { return tableNo; }
        set { tableNo = value; }
    }
}

Class 1

public partial class Class1 : Form
{
    private event OrderEventDelegate readyEvent;

    public Class1(HomeForm parent, int tableNo)
    {
        InitializeComponent();
        readyEvent -= new OrderEventDelegate(parent.readyOrder);
    }

    public void button_click()
    {
        OrderEventArgs readyOrderArg = new OrderEventArgs();
        readyOrderArg.TableNo = 1;
        readyOrderArg.Message = "123";
        readyEvent(this, readyOrderArg);
    }
}

Here readyEvent -= new OrderEventDelegate(parent.readyOrder);readyOrder() is the method which remove items in the list, which is located in the 'Homeform'.

Exception enter image description here

Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
Amila Iddamalgoda
  • 4,166
  • 11
  • 46
  • 85
  • Are you sure you mean this: `readyEvent -= new OrderEventDelegate(parent.readyOrder);` and not **`+=`** – RobH Mar 11 '14 at 09:46
  • In the application there is += delegate also..but after that this -= comes :) I didnt included the += one here,but my application has it – Amila Iddamalgoda Mar 11 '14 at 09:48

2 Answers2

1

It is possible to initialize C# events with an empty delegate. This way it can always be called safely without a null pointer check. As shown in this answer: https://stackoverflow.com/a/340618/2404788.

public delegate void OrderEventDelegate (Object sender, OrderEventArgs args) = delegate {};    
Community
  • 1
  • 1
Stephan Palmer
  • 835
  • 7
  • 18
0

If there's a possibility of something being null and you can do something about it/don't want to critically fail when it is, then check for it:

if (readyEvent != null) {
  readyEvent( ... );
}

But the point here, I suppose, is that you don't want this thing to be null; so you should subscribe a handler to the event. I'm not sure why you're trying to remove a new instance of the delegate handler, but to add one you would use +=.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129