Is it possible for the CLR to create Object X that inherits from Object Y where
- Object Y is of type Object
- All methods of Y are available to object X.
- Callers of Object X think they see all of Y’s objects
- Object X masks the methods above and does some ‘work’ prior to running each method
- That ‘work’ may include counting the number of calls, or some arbitrary code
- Object X should be able to work against any object (It’s OK if it doesn’t work against Sealed objects)
An alternate implementation might use Generics where Object T<Y> exposes all the methods, events, and properties of contained object Y
Yes. This is called proxying an object. Castle DynamicProxy is designed for doing exactly this. Krzysztof Koźmic has produced an excellent tutorial about it.
It works by creating an object (X in your scenario) at runtime which inherits from the object you want to proxy (object Y). You provided an object which implements
IInterceptorwhich gets called when certain methods are invoked – you specify these in a proxy generation options class.The only caveat is that the methods you wish to intercept must be virtual, but you can probably get around this by wrapping the object to proxy in another which does provide virtual methods (although I’d guess you probably want to proxy the object because doing this is a real pain).