0

i would like to run a method, every time certain values are changed on a object.

I was wondering if i could create a Custom attribute to add to the values i want to trigger my method, when their value is changed.

Fx:

public class Program
{
    public static void Main()
    {
        A a = new A("Hello", true);
        a.text = "Goodbye";
        a.check = false;
    }
}
public class A{
   public string text {get; set;}
   [RunMyMethod]
   public bool check {get; set;}

   public A(string t, bool c){
       this.text = t;
       this.check = c;
   }
}

public class RunMyMethod : System.Attribute
{
}

I am aware of the fact that i simply just go add something to every fields Set method, but the class i want to implement this on, is rather huge, and it wouldn't be pretty.

  • Does this answer your question? [Is it possible to implement Property Changed as Attribute?](https://stackoverflow.com/questions/25200516/is-it-possible-to-implement-property-changed-as-attribute) –  Feb 14 '20 at 10:19
  • 2
    In my opinion the proposed duplicate answer doesn't really cover the question since it doesn't go into an attribute option (which is possible by things like PostSharp). –  Feb 14 '20 at 10:31

1 Answers1

1

This is why we have field for!

So, first of all, change

public bool check {get; set;}

to

private bool _check;

And define Property for setting this value:

public bool Check
{
  get { return _check; }
  set
  {
    // here you can add your logic,
    // If this logic is common for every field, you
    // can wrap it in method and call it here.
    // Also here you can use variable named "value", which holds
    // value to be set.
    // At the end, set the value:
    _check = value;
  }
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • 1
    I think OP has already considered this approach: "I am aware of the fact that i simply just go add something to every fields Set method, but the class i want to implement this on, is rather huge, and it wouldn't be pretty." – Matthew Watson Feb 14 '20 at 10:16
  • @MatthewWatson But in my opinion it can be very pretty and tried to convince OP :) – Michał Turczyn Feb 14 '20 at 10:33
  • 1
    Completely ignores the attribute part of the question though which seemed the real goal of OP. Which is actually possible following this question: https://stackoverflow.com/questions/25200516/is-it-possible-to-implement-property-changed-as-attribute –  Feb 14 '20 at 10:41