Question: Is spying the setter of a property something that can be achieved via Reflection?

Let's say, for instance, that I have a method somewhere that receives the following:

```
private void LogPropertySetter(string propertyName, string newPropertyValue)
{
    Logger.Log("Property " + propertyName + " has been set to " + newPropertyValue);
}

```

And I have this property somewhere in the application that I want to observe:

```
public int FlyingCatsAmount { get; set; }

```

Note that I did deliberately not place a private/public set of variables here so that the solution applies to properties.

Could I add a call in the setter like that via Reflection or with any other API (in debug) that allows to modify the setter from code and not in AOP (PostSharp)? 

```
LogPropertySetter([getPropertyNameViaReflection], value);

```

Answer: 
If you are using .net 4.5 you can call a method and get the callerpropertyname

For instance:

```
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{}

```

From .net 3.5 to 4 you can use this method:

```
   protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> expProperty)
    {
        this.RaisePropertyChanged(((MemberExpression)expProperty.Body).Member.Name);
    }

```

and call it in the setter like:

```
    public string DisplayNameExtensionMobileNumber
    {
        get
        {
            return _DisplayNameExtensionMobileNumber;
        }
        set
        {
            _DisplayNameExtensionMobileNumber = value;
            RaisePropertyChanged(() => this.DisplayNameExtensionMobileNumber);
        }
    }

```
Pre-.NET 4.5, it is possible to get the current property name using the following:

```
private int _x;
public int X
{
    get { return _x; }
    set
    {
        _x = value;
        string propName = MethodInfo.GetCurrentMethod().Name.Substring(4);
        LogPropertySetter(propName, value);
    }
}

```

The CurrentMethod name in this case will be `set_X`, so take off the first 4 characters to get back to `X`.

There is a big caveat to this however in that the method will probably be optimized away by the compiler and so not work as you want it to. You can set the following attribute to stop it being inlined, but this can cause a performance penalty and is generally not recommended:

```
public int X
{
    get { return _x; }
    [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.NoInlining)]
    set
    {
        _x = value;
        LogPropertySetter(MethodInfo.GetCurrentMethod().Name.Substring(4), value);
    }
}

```

If you are using .NET 4.5, I would recommend going with Cadburry's suggestion.