Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Class Changed Event causing Object reference not set to an instance of an object

Tags:

c#

events

I need an event to fire when I change a property. When I run this code I get a Object reference not set to an instance of an object. What am I doing wrong? What is the correct way to instantiate an event, and fire it when a property is set?

public member:

public event System.EventHandler ClassChanged;

property set:

ClassChanged(this, EventArgs.Empty);
like image 535
Kevin Avatar asked Dec 16 '22 13:12

Kevin


2 Answers

You need to verify the event handler it not null first:

if (ClassChanged != null)
    ClassChanged(this, EventArgs.Empty);

But in general, you may want to wrap this up into a helper method like so:

private void NotifyClassChanged() {
    if (ClassChanged != null)
        ClassChanged(this, EventArgs.Empty);
}

Or possibly implement INotifyPropertyChanged instead.

like image 110
CodeNaked Avatar answered Jan 27 '23 01:01

CodeNaked


Try this:

System.EventHandler handler = this.ClassChanged;
if (handler != null)
{
    handler(this, EventArgs.Empty);
}
like image 45
user7116 Avatar answered Jan 27 '23 01:01

user7116