0

Let's say, we have an ordinary C# class with one auto get/set property.

public class Entity
{
       public String SomeProperty {get;set;}

}

Is there any event, that is raised and that I can evaluate, when the set method of the SomeProperty is called?

Is something like this possible in any way, maybe reflection?:

Pseudo Code, NO REAL CODE:

Entity e = new Entity();
e.SomeProperty.SetterCalled += OnSetterCalled;

private void OnSetterCalled(Sender propertyinfo)
{
    propertyinfo pi = propertyinfo;
    Console.Write (pi.Name);
}

I know, I could use CallerMember, but then I had to change the auto property.

Michael
  • 938
  • 1
  • 10
  • 34
  • You can add actual getter/setter methods. They get called every time the property is accessed - it's exactly what they're designed to do. – Ken White Dec 04 '14 at 23:25
  • 1
    I can think of a couple of really awful, hard-to-implement ways. But realistically speaking? No. The setter will almost guaranteed be optimized to a simple write to the field, and even if it didn't, there's no built-in mechanism for you to trap method calls. If you want notification, implement it via one of the many commonly-used techniques for such events. – Peter Duniho Dec 04 '14 at 23:25
  • @Ken White: Could you give a hint or URL where I could find informations on that? Is it possible with auto implemented get/set properties? – Michael Dec 04 '14 at 23:31

2 Answers2

3

No, there is no way to do this.

The setter is just this:

_backingVariable = value;

Assignment does not inherently invoke any methods. As it stands, there is no way to raise an event during a property set utilizing an auto-property.

You can change the code at compile time using something like the technique described in: https://stackoverflow.com/a/18002490/1783619

But otherwise, there is no way to do this.

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

I would recommend looking into:

INotifyPropertyChanged

Here is a great walkthrough:

Implementing INotifyPropertyChanged - does a better way exist?

Community
  • 1
  • 1
Jason White
  • 218
  • 1
  • 5
  • For the moment, this is the best hint/answer, because the solution offered in the link seems to be cleanest way. – Michael Dec 04 '14 at 23:44