Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an event

Tags:

c#

.net

events

I have a class with an event like this

public class A
{
    public event Func<string, string> Message;

    public void Calling()
    {
        Message("Hello world!");
    }
}

If I call the Calling() method and no one has subscribed to the Message event yet, it is null and throws an exception.

How can I initialize my event?

like image 944
Alexander Leyva Caro Avatar asked Dec 03 '22 18:12

Alexander Leyva Caro


1 Answers

You don't init your event rather you need to check for null in your Calling method:

public void Calling()
{
    if (Message != null)
        Message("Hello World!");
}
like image 169
Brian Driscoll Avatar answered Dec 14 '22 15:12

Brian Driscoll