Property reusability

Topics: C# Language Design
Oct 26, 2014 at 8:16 AM
All we frequently implement this.
public Person
{
    private String _Name;
    public String Name
    {
        get { return _Name; }
        set 
        {
            if (_Name == value) return;
            _Name = value;
            this.OnPropertyChange(nameof(Name));
        }
    }
    private Int32 _Age = 0;
    public Int32 Age
    {
        get { return _Age; }
        set 
        {
            if (_Age == value) return;
            _Age = value;
            this.OnPropertyChange(nameof(Age));
        }
    }
    //Other properties...
}
Duplicate code.I think it is missing feature to reuse property implementation.
So, I suggest
public property T PropertyWithEvent
{
    get { field = value;}
    set 
    {
        if (field == value) return;
        field = value;
        this.OnPropertyChanged(nameof(PropertyWithEvent));
    }
    void OnPropertyChanged(String propertyName);
}
field is keyword that represent backing field(like _Name).
And compiler automatically generate this backing field.
nameof(PropertyWithEvent) will be a String of property name.
We can use this as below.
public class Person
{
    public property String PropertyWithEvent Name;
    public property Int32 PropertyWithEvent Age;
    void OnPropertyChanged(Sring propertyName)
    {
        //implementation....
    }
}
PropertyWithEvent require the class that use this property to have OnPropertyChanged method.


That reduce cost to implement property.
And improve DRY principle.
Oct 26, 2014 at 9:53 AM
There's already a discussion for a more general solution here: http://roslyn.codeplex.com/discussions/550266
Oct 27, 2014 at 4:04 PM
Hi Olmo.

We talk same issue but different solution.
So, I create new thread.

I think that your solution can not call class instance method(OnPropertyChanged...etc).
My solution can call.