juststressed
juststressed

Reputation: 89

How to invoke a method when a property of a nested object changes?

Say I have the class MyObject:

public class MyObject 
{
     public SomeOtherObject SomeOtherObject { get; set; }

     public void MyMethod()
     {
          //Do something
     }
}

Where MyObject.SomeOtherObject is as follows:

public class SomeOtherObject 
{
     public string Information { get; set; }
}

Assume that the property SomeOtherObject.Information is set by an instance of another class.

How can I automatically invoke MyObject.MyMethod() when MyObject.SomeOtherObject.Information changes?

Upvotes: 0

Views: 464

Answers (2)

drim4591
drim4591

Reputation: 108

Define an event callback. In SomeOtherObject;

public EventCallback OnInformationChangedEvent { get; set; }

I am not sure exactly what is setting the Information property. But ultimately you need a line somewhere in you SomeOtherObject class that does this;

await OnInformationChangedEvent.InvokeAsync();

You could even do this in the setter of the property itself.

In the parent MyObject you can pass the method that you want to be invoked. And refine your method as follows;

public void MyMethod(object sender, EventArgs e)
{
     //Do something
}

And where you define SomeOtherObject;

SomeOtherObject.OnInformationChangedEvent += MyMethod;

There are other ways to do it (for example defining your own Observer pattern, which I think is what .NET is doing underneath anyway).

I didn't run that code so my syntax might be slightly off, but you should be 99% there with that.

Upvotes: 1

Xaver
Xaver

Reputation: 1041

I recommend using events. In the class MyObject, you can specify an event and register an event handler for this event - either use MyMethod as event handler or create another method that calls MyMethod.

Then, rewrite SomeOtherObject:

public class SomeOtherObject 
{
     public string Information
     {
         get => _Information;
         set
         {
             _Information = value;
             // add code to fire the event
         }
     }
     private string _Information;
}

Upvotes: 1

Related Questions