Domanda

I am new delegates and event so i tried below code but i got NullReference exception

public class Class1
{
    public delegate void load();

    static void Man( )
    {
        Console.WriteLine("Man");

    }

    static void Dog()
    {
        Console.WriteLine("Dog");

    }

    load sas = new load(Man);


    public event load even;

    void Display()
    {
        even();
    }

    static void Main()
    {
        Class1 ss = new Class1();
        ss.Display();

    }
}

where i made error .... thanks....

È stato utile?

Soluzione

Event variables need to be assigned as well, before you could start calling them.

Your event variable called even has not been assigned, so it remains null. You need to assign it somewhere - for example, in your Main method:

static void Main()
{
    Class1 ss = new Class1();
    ss.even += Man;
    ss.Display();
}

Your sas variable, on the other hand, is assigned, but it remains unused. You can remove its declaration from the program.

Here is a demo of your corrected programs running.

Event processing code that goes to production needs to null-check events before making a call:

void Display()
{
    if (even != null) even();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top