Can you hack this out?

time to read 2 min | 371 words

I recently had to take a really deep look into how to cheat the CLR, that brought about some interesting discoveries, including the fact that it is, surprisingly, possible to do so.

Let us say that you have this code in some 3rd party assembly that you cannot modify:

internal interface IRunner
{
void Execute();
}

public sealed class AssemblyRunner : IRunner
{
void IRunner.Execute()
{
Console.WriteLine("executing");
}
}

public class CompositeRunner<T> where T : new()
{
public void Execute()
{
if(!typeof(IRunner).IsAssignableFrom(typeof(T)))
throw new InvalidOperationException("invalid type");
var runner = (IRunner)new T();
Console.WriteLine("starting");
runner.Execute();
Console.WriteLine("done");
}
}

Can you get the CompositeRunner to output:

    • starting
    • before executing
    • executing
    • after executing
    • done

The real problem was a bit harder, but this is a good start.