C# next should support raising PropertyChanged without requiring back field

As you know, we can define C# class properties using a very simple syntax – that’s great:

public <Type> MyProperty {get; set;}

On the other side, [CallerMemberName] attribute has been recently introduced helping us (among a few other things) to implement INotifyPropertyChanged a little easier, when needed – that’s great too:

private <Type>myField;
public <Type>MyProperty 
{
  get { return myField; } 
  set 
  { 
    myField = value; 
    OnPropertyChanged(); 
  } 
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName=null)
{
    if (PropertyChanged != null && propertyName != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

However, as you can see, mixing the first and second great things doesn’t work. In the second example I had to define a field verbosely although I don’t use it except for reading and updating its value, since there was no other way to call OnPropertyChanged() at the end of the property setter.

Moreover, validations and other common initialization routines may actually occur as often as raising property change events, and therefore we should also consider those cases when trying to find an easy way to express the property setter with a lighter syntax.

I would eventually expect a syntax like below. What do you think? (Maybe others already proposed a similar approach, but I haven’t looked much – my apologizes if you also have had the same idea and didn’t mention your post – it was not intentional.)

// Does NOT work in current C#! It's a feature proposal.
public <Type>MyProperty 
{
  get; 
  set
  {
    if (!IsValid(value))
      return;
    yield set; // new special statement to indicate where setting the field value should occur
    OnPropertyChanged();
  }
}
Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, C# and tagged , , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s