Search code examples
c#event-handlingnull-pointer

Subscribe eventhandler to reference that is null


I'm currently writing an application in which I deserialize relatively large objects (which can also grow in size, depending on what the user adds to them). I don't want to load all of them into RAM since that might cause problems when there are many of them.

Anyway, I want to handle events raised by the loaded instance of that class if there is one which is already my problem.

How can I subscribe an event handler to an object that is still null?

I think of something like "if there is an object and it raises that event handle it with that method".



Here is some sample code and the only approach I could think of though I already thought it couldn't work..

public class MyClassA
{
    public event EventHandler PropertyChanged;

    private string someProperty
    public string SomeProperty
    {
        set
        {
            someProperty = value;
            PropertyChanged?.Invoke(this, EventArgs.Empty);
        }
    }

    public static MyClassA Load(string path)
    {
        /*...*/
    }
}

public class MyClassB
{
    public MyClassA InstanceOfA { get; private set; }        

    public MyClassB
    {
        //InstanceOfA.PropertyChanged += MyEventHandler; Not working, NullReference
    }

    // Handle InstanceOfA.PropertyChanged here...
    public void MyEventHandler(object sender, EventArgs e)        
    {
        /*...*/
    }
}


Solution

  • Of course you cannot subscribe an event handler to an object that is still null,but you can subscribe when you assign a non null value to it.
    Just use a property and a backing field:

    public class MyClassB
    {
        private MyClassA myVar;
    
        public MyClassA InstanceOfA
        {
            get { return myVar; }
            private set
            {
                myVar = value;
                if (myVar != null)
                    myVar.PropertyChanged += MyEventHandler;
            }
        }
    
        public void MyEventHandler(object sender, EventArgs e)
        {
    
        }
    }