0

I want to implement a mechanism that change bool variable to true any time I call to set function (I have couple of setters functions). Sample Code:

private bool isSomethingChanged = false;

public void SetName(string _name)
{
    // change name
}

I don't want to write: isSomethingChanged = true; at the end of all setters functions. I want it to happen automatically. Is it possible ?

Abbas
  • 14,186
  • 6
  • 41
  • 72
Alon
  • 35
  • 1
  • 5

1 Answers1

0

First - it's not enough to simply set isSomethingChanged to true at the end of setter - you should also verify that something really changed. E.g.

public void SetName(string _name)
{
    if (name == _name) // check
       return;   

    name = _name;
    isSomethingChanged = true;
}

Back to solving your problem - there is no built-in feature to set some variable automatically when any of methods was called. You can use code generation for that. E.g. you can use AOP framework PostSharp. Here is implementation of INotifyPropertyChanged interface with this framework, which does almost same as you want: AOP Implementation of INotifyPropertyChanged. The only difference is you should set variable value instead of raising event.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Couldn't you rewrite it a little less simple? Like: `public void SetName(string _name) { if (name != _name) { name = _name; isSomethingChanged = true; }`. I just like to avoid 'useless' `return` statements. :) – Abbas Apr 03 '14 at 08:52
  • 2
    @Abbas actually there is no difference. But I like [guard conditions](http://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html) for simple single-level code identation, also I prefer positive comparision (equals) to negative comparisons (not equals) - but that matter of taste maybe :) – Sergey Berezovskiy Apr 03 '14 at 08:55
  • 2
    I agree with you @SergeyBerezovskiy. The code Abbas suggested is, to me, less readable, because you could potentially end up with a huge nested block. For me the `} } } } } } } } }`-end of a method is horrible.. – default Apr 03 '14 at 09:07
  • @Default / SergeyBerezovskiy Ok, I agree with both of you. This might indeed be cleaner. :) – Abbas Apr 03 '14 at 09:22