tags:

views:

64

answers:

6

Hi, I have a class library in C# which is compiled into a dll. Is it possible to change something in a compiled class method for a specific project without touching the original source code or creating a new class by inheritance?

A: 

No, essentially.

Your best option should be, as you said, to derive your own class and override the method in question (assuming it is not sealed).

You could add functionality to the class by using an extension method.

David Neale
A: 

I don't think so. You could create an extension method, though it won't have access to private/protected/internal members.

mdresser
A: 

If you have the source code but don't want to change it - branch it.

If you're OK with a slightly different method signature, write an extension method.

If none of the above work for you, and the class must have the same name, inherit with a class of the same name, override, and place the class in a different namespace. Differentiate from the original by namespaces. Just inheriting normally will probably be easier to maintain, though...

If you're still not happy, I can't help you.

Tomas Lycken
A: 

Not to the best of my knowledge. Can you explain more about your scenario as to why you would need to do something like this?

InSane
A: 

With some heavy hacking involving reflection and reflection emit into a new application domain, sure. But I doubt it would be worth it.

Pontus Gagge
+2  A: 

It's technically possible using code rewriting via a technique used by frameworks like Moles. However, I wouldn't recommend this. Instead, you'd be better off with an wrapper class that delegates calls to a contained object and overrides the behavior you're after for only the specific methods that must change.

Dan Bryant
Thanks, could you give me an example of a wrapper class? Another problem I have is the compiled classes need to call other methods in those classes so if I override them they need to call the overridden method.
CL4NCY
Wrapping will only work for your use of the class, as you can construct and use the wrapper when you access it. Other methods on the wrapped class won't be aware of the wrapper, so that won't work as you're intending. You might want to reconsider your design to sidestep this issue entirely, as getting into IL rewriting to inject detours will probably make your code hard to maintain.
Dan Bryant