1

Just wondering if it's possible to call a method using property attribute. Basically, I want to set state of the entity when any of the public property changes.

Like we have following code

public class Contact : EntityBase
{
    [NotifyChange]
    public string FirstName { get; set; }

    private void ChangeState()
    {
       EntityState = EntityState.Modified;
    }
}

And when we call

var c = new Contact();
c.FirstName = "John";

before (or after) setting value of FirstName, it call EntityState() function.

Any idea?

Parth Patel
  • 307
  • 1
  • 6
  • 19

2 Answers2

2

It would be much simpler if property is rewritten as:

public class Contact : EntityBase
{

    private string _firstName;

    [NotifyChange]
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            ChangeState();
            _firstName = value;
        }
    }

    private void ChangeState()
    {
       EntityState = EntityState.Modified;
    }
}
Abhinav
  • 2,085
  • 1
  • 18
  • 31
  • 2
    I think the attribute `[NotifyChange]` is some pseudo code which has no meaning. – Hamlet Hakobyan Apr 15 '14 at 05:03
  • Thought so too but left it there since I did not know the exact use. Semantically, it wouldn't make sense to use the attribute. – Abhinav Apr 15 '14 at 05:06
  • I'm already aware of this (and for the above example we don't need NotifyChange attribute as it was there to call ChangeState function) but in many classes I have more than 20 properties and every time declaring private variable and using it to set and get property is too much work. I'm just thinking of some smart way to keep track of the property change. If nothing would be possible then I have no other change but to use the way you mentioned. – Parth Patel Apr 15 '14 at 05:32
  • @ParthPatel In That cases there are a lot of refactoring tools which makes life easy. – Hamlet Hakobyan Apr 15 '14 at 05:48
  • @Hamlet Hakobyan, refactoring tools like? – Parth Patel Apr 15 '14 at 06:06
  • For instance Resharper. – Hamlet Hakobyan Apr 15 '14 at 07:06
0

Try this:

public class Contact : EntityBase
{
    private string _firstName;
    public string FirstName
    {
        get {return _firstName}
        set
          {
              _firstName = value;
              EntityState(); // maybe here must by ChangeState()
          }
    }

    private void ChangeState()
    {
       EntityState = EntityState.Modified;
    }
}
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68