-1

I want to create an event in C# but I'm getting this error:

An unhandled exception of type 'System.NullReferenceException' occurred in shei graii.exe

Additional information: Object reference not set to an instance of an object.

Server code:

public class mobile
{
    public delegate void chargeEvent();
    public event chargeEvent sampleEvent;

    private byte _charge;

    public byte charge
    {
        set
        {
            _charge = value;
            if (_charge <= 15)
            {
                sampleEvent(); // the error line
            }
        }
    }
}

Client code:

mobile mob = new mobile();

mob.charge = 14;

mob.sampleEvent += new mobile.chargeEvent(input);

Input code:

public void input()
{
    MessageBox.Show("battery low");
}

1 Answers1

1

You get the NullReference error because you try to invoke the event before setting it. So try this instead:

mobile mob = new mobile();

mob.sampleEvent += new mobile.chargeEvent(input);

mob.charge = 14;

This is as far as we can go with the limited code you provided.

Ricardo González
  • 1,385
  • 10
  • 19