Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChanged and Auto-Properties

Tags:

c#

.net

vb.net

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.

like image 270
HCL Avatar asked Jul 27 '10 19:07

HCL


People also ask

What are auto properties?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is the purpose of INotifyPropertyChanged?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .

What is the point of auto properties?

properties allow your access to be polymorphic (inheritors can modify access if the property is virtual) if you so choose. auto-properties are nice when you're dealing with simple get/set operations. if you do more complicated operations inside your get / set, then you can't use the auto-property.

When can we use automatic properties?

11 Answers. Show activity on this post. Automatic Properties are used when no additional logic is required in the property accessors.


2 Answers

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);} } 
like image 184
crea7or Avatar answered Oct 08 '22 16:10

crea7or


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.

like image 23
ChrisF Avatar answered Oct 08 '22 15:10

ChrisF