In java it's possible to dynamically implement an interface using a dynamic proxy, something like this:
public static <T> T createProxy(InvocationHandler invocationHandler, Class<T> anInterface) {
if (!anInterface.isInterface()) {
throw new IllegalArgumentException("Supplied interface must be an interface!");
}
return (T) Proxy.newProxyInstance(anInterface.getClassLoader(), new Class[]{anInterface}, invocationHandler);
}
Is there an equivalent in .Net?
There are several libraries that implement this in .NET. Here's a list of them, with a benchmark.
The most widely used one is the Castle Project's Dynamic Proxy, which is also used by several (or at least 1) mocking frameworks. Keep in mind that methods (and sugared-up methods like properties) are not virtual by default in dotnet, so that can create some headaches if you weren't anticipating it in your class design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With