Interface Based Anonymous Types

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

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

Something in the lines

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

Situations in which I see them useful are to specify method parameters that are interface types, and there is too much code when creating a class type.

For example, consider the following:

    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 will this be achieved if the Cleanup method had an interface as a parameter in the above code without writing a class definition? (I think Java allows expressions like new Interface () ...)

+5
source share
3 answers

. IInterface , Reflection.Emit , , -, / Action<...>/Func<...> ( Expression), .

, , . , .

+3

impromptu-interface. Duck Typing.

+5
private void CleanUp(Func<string> obj){
  Console.WriteLine("str from delegate " + obj.Invoke());
}

public void RunTest(){
   Cleanup(() => "hello from anonymous type");
 }
  • although not implemented for the interface ...
0
source

All Articles