Search code examples
c#eventsnotificationsobserver-patternobservers

C# - Implement property observation afterwards


I have a question about the observation of properties of an object.

For example, I have a class like this:

public class MyProperties
{
  public string Prop1 { get; set; }
  public int Prop2 { get; set; } 
}

My wish is to get a notification if one of the properties of MyProperties are changed. My vision is something like this:

//I have an instance
MyProperties Prop = new Myproperties();
//And add a listener to the properties
Prop.Prop1.AddNotification(APropertyChanged);
Prop.Prop2.AddNotification(APropertyChanged);

//I have a eventhandler in my code
public void (object Sender, EventArgs e)
{
  //Sender is the Property
}

I don't want to change any code in MyProperties. Is there any way to achive something like this .. or is this idea totally idiotic?


Solution

  • Here is my solution. Thanks to the tip of @romain-aga.

    Fody PropertyChanged allows to change the code of properties during compilation. If I have the class:

    public class MyProperties
    {
        public string Prop1 { get; set; }
        ...
    }
    

    Fody would compile this code:

    public class MyProperties
    {
        string prop1;
        public string Prop1
        {
            get { return prop1; }
            set
            {
                if (value != prop1)
                {
                    prop1 = value;
                    OnPropertyChanged("Prop1");
                }
            }
        }
        ...
    }
    

    Via reflection, it is possible to add a method to the generated PropertyChanged event:

    EventInfo Event = typeof(MyProperties).GetEvent("PropertyChanged");
    MethodInfo Method = //The methode of the handler you want
    Delegate Handler = Delegate.CreateDelegate(Event.EventHandlerType, this, Method);
    Event.AddEventHandler(IntanceOfMyProperties, Handler);