5

Can I create anonymous implementations of an interface , in a way similar to the way

delegate() { // type impl here , but not implementing any interface}

Something on the lines of

new IInterface() { // interface methods impl here }

The situations where I see them to be useful are for specifying method parameters which are interface types, and where creating a class type is too much code.

For example , consider like this :

    public void RunTest()
    {
        Cleanup(delegate() { return "hello from anonymous type"; });
    }

    private void Cleanup(GetString obj)
    {
        Console.WriteLine("str from delegate " + obj());
    }

    delegate string GetString();

how would this be achieved if in the above code , the method Cleanup had an interface as a parameter , without writing a class definition ? ( I think Java allows expressions like new Interface() ... )

Bhaskar
  • 7,443
  • 5
  • 39
  • 51

3 Answers3

5

You may take a look at impromptu-interface. Allow you to wrap any object with a Duck Typing Interface.

Kalman Speier
  • 1,937
  • 13
  • 18
  • I'd like to add it really is any object, including dynamic objects and anonymous objects. – jbtule Mar 02 '11 at 23:41
  • I would like to first understand how this thing works exactly .. +1 for the interesting link – Bhaskar Mar 03 '11 at 00:19
  • @Bhaskar it emits a lightweight proxy that uses the DLR to forward invocation to the orignal object. Essential it does the nontrivial work @Marc-Gravell was referring and uses the DLR as glue between the interface and an implementation, dynamic or otherwise. – jbtule Mar 03 '11 at 01:11
  • @jbtule, exactly. Also I think it's way faster than reflection. – Kalman Speier Mar 03 '11 at 06:58
3

There is no standard language syntax for that. To create an implementation of IInterface on the fly you could use Reflection.Emit and maybe something involving generics and/or Action<...>/Func<...> (with or without Expression), but it is a non-trivial amount of work.

Essentially, this is what many of the mocking frameworks do. Look to them, perhaps.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0
private void CleanUp(Func<string> obj){
  Console.WriteLine("str from delegate " + obj.Invoke());
}

public void RunTest(){
   Cleanup(() => "hello from anonymous type");
 }
  • although not really implementing for an Interface...
Sunny
  • 6,286
  • 2
  • 25
  • 27