Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extension method to Property Accessor

We are doing alot of INotifyPropertyChanged implementation in our View Models and quite frankly are getting tired of having to fire the property changed events explicitly in our code for both inconvenience and aesthetic reasons.

I want to put an extension on the setter of our property, making the resulting code look like:

public string LazyAccessor
{
  get;
  set.notify();
}

Is there a way to do this? Can we invent one if there isn't?

like image 501
Hank Avatar asked Oct 19 '12 14:10

Hank


4 Answers

Check out NotifyPropertyWeaver. This will modify your code during the build process to have your properties implement the INotifyPropertyChanged pattern.

This is available as a Visual Studio Extension

like image 152
cadrell0 Avatar answered Oct 11 '22 00:10

cadrell0


Aspect oriented programming could be solution of your problem.

See Aspect Oriented Programming in C#. And some examples here: http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS

Your "set.notify()" could work with some Reflection, but I don´t think this would be good solution and you will still need to implement getter and setter.

like image 33
Ondra Avatar answered Oct 11 '22 01:10

Ondra


Extension methods can only be added to types. The getters and setters on automatic properties are converted into methods with backing variables by the compiler, so there is no way to put an extension method on them.

like image 42
goric Avatar answered Oct 11 '22 02:10

goric


Is there a way to do this?

No, there isn't, not like you posted. Extension methods operate on types, not getters or setters.

Can we invent one if there isn't?

That would require changes to the C# specification - not a likely thing to happen.

There are other approaches that you can take to ease this - using a base class with a method that will make the boiler plate calls for you for example.

like image 2
Oded Avatar answered Oct 11 '22 02:10

Oded