Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Property Setter method at runtime

Tags:

c#

reflection

I have a number of objects that all share a common base class, I wish to intercept all calls that set Property values and record if these have been set on a per instance basis.

Can I replace the Set Method of a Property at runtime with Reflection?

like image 986
IanNorton Avatar asked Dec 04 '10 07:12

IanNorton


2 Answers

One approach there is to make the property virtual, and at runtime create a subclass via reflection-emit that override the properties, adding your code. However, this is advanced, and requires you always make sure to create the subclass (so no "new" in code).

However; I wonder if simply implementing INotifyPropertyChanged and handling the event is simpler. The other option is to just build the handling into the regular class in the first place. There are some ways of making this less repetitive, especially if you have a common base-class where you could add a

protected void SetField<T>(ref T field, T value)
{
    if(!EqualityComparer<T>.Default.Equals(field,value))
    {
        field = value;
        // extra code here
    }
}

With

private int foo;
public int Foo {
    get { return foo; }
    set { SetField(ref foo, value); }
}
like image 138
Marc Gravell Avatar answered Oct 06 '22 15:10

Marc Gravell


If your base class derives from ContextBoundObject you can create your objects in a different Context (within the same AppDomain) and intercept method calls (which is what properties are) and insert your own message sink into the remoting sink chain.

heres one example

http://www.codeproject.com/KB/cs/aspectintercept.aspx

like image 39
Dean Chalk Avatar answered Oct 06 '22 15:10

Dean Chalk