Return F # Interface from C # Method

I recode some things from F # to C # and ran into a problem.

In the F # example, I have something like this:

let foo (x:'T) =
    // stuff
    { new TestUtil.ITest<'T[], 'T[]> with
        member this.Name input iters = "asdfs"
        member this.Run input iters = run input iters
      interface IDisposable with member this.Dispose() = () }

Now in my version of C # I have.

public class Derp
{
    // stuff

    public TestUtil.ITest<T, T> Foo<T>(T x)
    {
        // ???
        // TestUtil.ITest is from an F# library
    }
}

How do I recreate this F # functionality in C #? Is there a way to do this without completely redefining the ITest interface in C #?

+4
source share
1 answer

C # does not support the definition of an anonymous implementation of such an interface. Alternatively, you can declare some inner class and return it instead. Example:

public class Derp
{
    class Test<T> : TestUtil.ITest<T, T>
    {
        public string Name(T[] input, T[] iters) 
        {
            return "asdf";
        }
        public void Run(T[] input, T[] iters)
        {
             run(input, iters);
        }
        public void Dispose() {}
    }

    public TestUtil.ITest<T, T> Foo<T>(T x)
    {
         //stuff
         return new Test<T>();
    }
}

Note that I'm not sure I got the types correctly for your F # code, but this should be a general idea.

+6
source

All Articles