0

I got an enum:

public enum sprog{
   dansk,
   svensk,
   norsk
}

In a method I would raise an event and use the enum to carry information:

public delegate void BrugerSprogChanged(Object sender, Sprog sprog);
class clazz
{
    public event BrugerSprogChanged brugerSprogChanced;
    public clazz(){}

    private void comboBoxDokumentSprog_SelectedIndexChanged(object sender, EventArgs e)
    {
        Sprog sprog = FindSprog((string)((ComboBox)sender).SelectedItem);
        dokumentSprogChanged(this, sprog); // <- here we have the problem
    }
}

When the code shall raise the event I get an exception when dokumentSprogChanged(this, sprg) is called:

*"NullReferenceException was unhandled by user code

Object reference not set to an instance of an object"

"this" and "sprog" are not null.

Any suggestions?

The easy way is to drop the unem and use an integer/string instead, but then I end up with some ugly code.

Anders Finn Jørgensen
  • 1,275
  • 1
  • 17
  • 33

2 Answers2

3

Normally to call an event you have to check if it's handler is not null:

var handler = dokumentSprogChanged; // take a local reference

if (handler != null)
{
    dokumentSprogChanged(this, sprog);
}

This way you can raise it safely.

EDIT

You need to register the event like this:

public event BrugerSprogChanged brugerSprogChanced;

....
brugerSprogChanced += class_brugerSprogChanced;
....

void class_brugerSprogChanced(object sender, EventArgs e)
{
    // handle there
}
Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
  • Thanks for your answer. The problem now is that the handler is null. I use another event: public delegate void ValgteSprogChanged(bool da, bool fo); which work without problems. Maybe it's illigal to use an enum in a delegate/event – Anders Finn Jørgensen May 06 '14 at 11:38
1

Try this:

class clazz
{
    public event BrugerSprogChanged brugerSprogChanced;
    public clazz(){}

    private void comboBoxDokumentSprog_SelectedIndexChanged(object sender, EventArgs e)
    {
        Sprog sprog = FindSprog((string)((ComboBox)sender).SelectedItem);
        if (dokumentSprogChanged != null)
        {
            dokumentSprogChanged(this, sprog); // <- here we have the problem
        }
    }
}