views:

214

answers:

2

Let's assume we have the following class:

public class tx_fct
{

    int _ok;

    public int ok 
    {
        get
        {
            return _ok;
        }
        set
        {
            _ok = value;
        }
    }
}

How can I override the getter using reflection?

The getter doesn't seem to be in tx_fct1.ok.GetType().GetMethods().

When I do get access to the getter, how do I insert my own getter code?

+4  A: 

Reflection API provides only methods to create classes and methods, but not modify existing ones. It is not possible to modify existing method in runtime. All you can do is to inject some IL into assembly which has not yet been loaded into the AppDomain.

Vitaliy Liptchinsky
+2  A: 

Mainly, you would need inheritance:

public class tx_fct {
    int _ok;
    public virtual int ok {
        get { return _ok; }
        set { _ok = value; }
    }
}
class custom_fct : tx_fct {
    public override int ok {
        get {
            Console.WriteLine("get");
            return base.ok;
        }
        set {
            Console.WriteLine("set");
            base.ok = value;
        }
    }
}

Note that you can create subclasses at runtime using AssemblyBuilder, TypeBuilder, etc - but it isn't fun, and should be reserved for when you absolutely need it.

Marc Gravell