Chiritescu Adrian Chiritescu Adrian - 10 months ago 39
C# Question

Is it possible to create an extension method that is called when the object is created?

I cannot modify the object I am working with and I need a method but I really want it to be called when the object is created. So I was thinking that a extension method would be good here, however I don't know if it is possible but, if it is, then how?

Answer Source

No, this is not possible. If it was it would be very unreliable because it would depend on whether you included relevant extension with using or not. That's actually general problem of extension methods but here it's even worse as it would never cause compile time error.

The best way how to implement this is probably using the factory pattern to indirectly construct the object and inject that factory in the code. This still doesn't solve the problem of existing code though.