0

I have an object that contains a public Action to call an update method within another class, whenever a property changes in the first class. It looks something like this:

public class FirstClass {

  public Action Update;

  private string _description;

  public string Description
  {
    get { return _description; }
    set
    {
        if (_description == value) return;
        _description = value;
        Update();
    }
  }
}

There are about 30 different properties that this needs to be applied to. Is there a more efficient way to accomplish this?

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
Dezzamondo
  • 2,169
  • 2
  • 20
  • 33
  • 7
    That really looks like a less-specific version of [`INotifyPropertyChanged`](https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx) and you might be interested in this answer: [Implementing INotifyPropertyChanged - does a better way exist?](http://stackoverflow.com/a/1316417/996081) – cbr Jan 09 '17 at 15:36
  • Possible duplicate of [Implementing INotifyPropertyChanged - does a better way exist?](http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist) – M.kazem Akhgary Jan 09 '17 at 15:42
  • You can also just fire an event. (If there are registered listeners) – JWP Jan 09 '17 at 16:17

1 Answers1

2

This looks like you want to use Aspect Oriented Programming (AOP). I currently use Postsharp (http://www.postsharp.net) to achieve this, but there are other alternatives too. The description below relates to Postsharp - other implementations may differ.

Create an interface that can provide the update action.

public interface IUpdateAction {
   public Action Update { get; }
}

then create an aspect, this is implemented as an attribute

[PSerializable] 
public class UpdateActionAttribute : LocationInterceptionAspect 
{ 

  public override void OnSetValue(LocationInterceptionArgs args) 
  { 
    if ( args.Value != args.GetCurrentValue() )
    {
      args.Value = args.Value;
      args.ProceedSetValue();
     ((IUpdateAction)args.Instance).Update();
    } 
  } 
}

Then you can apply the aspect to your class

public class FirstClass : IUpdateAction {

  public Action Update {get; set;}

  [UpdateAction]
  public string Description {get;set;}

}

When the code is compiled the rewriter will kick in and implement the aspect for the assigned properties.

You can take this further by using multicasting to apply it all properties or a filtered list.

Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • I like the solution, but aren't too keen on using PostSharp. I guess I was hoping to be able to spin a custom attribute in place of PostSharp, but it got me looking in the right direction. Thanks Bob – Dezzamondo Jan 23 '17 at 13:13