Search code examples
c#classreflectionsystem.reflection

Passing C# parameters which can "fit" an interface, but do not actually implement it


Note: I know this is an awful idea in practice; I'm just curious about what the CLR allow you to do, with the goal of creating some sort of 'modify a class after creating it' preprocessor.

Suppose I have the following class, which was defined in another assembly so I can't change it.

class Person {
    public string Greet() => "Hello!";
}

I now define an interface, and a method, like the following:

interface IGreetable {
    string Greet();
} 

// ...

void PrintGreeting(IGreetable g) => Console.WriteLine(g.Greet());

The class Person does not explicity implement IGreetable, but it could do without any modification to its methods.

With that, is there any way whatsoever, using Reflection, the DLR or anything else, in which an instance of Person could be passed successfully to PrintGreeting without modifying any of the code above?


Solution

  • Try to use the library Impromptu-Interface

    [The Impromptu-Interface] framework to allow you to wrap any object (static or dynamic) with a static interface even though it didn't inherit from it. It does this by emitting cached dynamic binding code inside a proxy.

    This allows you to do something like this:

    var person = new Person();
    var greeter = person.ActLike<IGreetable>();