Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous types based in Interface [duplicate]

Tags:

c#

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() ... )

like image 723
Bhaskar Avatar asked Mar 02 '11 23:03

Bhaskar


2 Answers

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

like image 111
Kalman Speier Avatar answered Oct 23 '22 02:10

Kalman Speier


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.

like image 37
Marc Gravell Avatar answered Oct 23 '22 02:10

Marc Gravell