INotifyPropertyChanged and Auto-Properties

Is there a way to use INotifyPropertyChanged with auto-properties? Maybe an attribute or something other, not obvious to me.

public string Demo{
    get;set;
}

For me, auto-properties would be an extremely practicall thing, but almost always, I have to raise the PropertyChanged-event if the property value has been changed and without a mechanism to do this, auto-properties are useless for me.


Solution 1:

In .NET 4.5 and higher it can be made somewhat shorter:

private int unitsInStock;
public int UnitsInStock
{
    get { return unitsInStock; }
    set { SetProperty(ref unitsInStock, value);}
}

Solution 2:

It's something you would have to code yourself. The closest you could get would be something like this implementation on Code Project that uses a custom attribute and aspect orientated methods to give this syntax:

[NotifyPropertyChanged] 
public class AutoWiredSource
{ 
   public double MyProperty { get; set; } 
}

Someone once proposed on Microsoft Connect a change to the C# specification implement this:

class Person : INotifyPropertyChanged
{
    // "notify" is a context keyword, same as "get" and "set"
    public string Name { get; set; notify; }
}

But the proposal has been now closed.

Solution 3:

There's no built-in mechanism to do this. Something like PostSharp would likely be able to add something like this for you (or Mark Gravell's HyperDescriptor, if you're just interested in making this databinding-aware).