Skip to content

Feature request: Anonymous types that implement interfaces #13

@nvivo

Description

@nvivo

It would be very useful if C# anonymous types could implement interfaces, including methods. This would make a huge difference when developing using interface driven design. It would also allow for very easy mocking in unit tests.

interface IFooBar {
    string Foo { get; }
    int Bar(string s);
}

void MethodA () {
    // explicitly typed
    var myFooBar = new IFooBar {
        Foo = "xyz",
        Bar = s => s.Length
    };

    MethodB(myFooBar);
}

IFooBar MethodB(IFooBar fooBar) {
    // implicit typed
    return new {
        Foo = "abc",
        Bar = fooBar.Bar
    };
}

In TypeScript and other dynamic languages, this has proven to be really useful and reduces a lot of boilerplate code.

It seems that implementing this in C# wouldn't break any rules as anonymous types are already classes internally, and the compiler could just make it implement the interface and use the same rules for checking type.

The only issue I can think right now is the method implementation. How to differ between a method and a property that is a delegate:

interafce IFoo {
    int Bar(int i);
    Func<int, int> Baz { get; }
}

void IFoo GetFoo() {
    return new {
        Bar = i => 1, // ?
        Baz = i => 2; // ?
    }
}

It seems that from the perspective of the C# consumer it wouldn't make much difference, as both can be called using the same syntax (obj.Bar() or obj.Baz() ), but the compiler needs to know this.

This could be solved by either adding a new syntax to this implementation:

void IFoo GetFoo() {
    return new {
        Bar(int i) => 1,   // method
        Baz = i => 2;  // deletage
    }
}

Or by just defaulting to methods unless the interface calls for a property. That would make the first example with the same code valid, and I guess would make the syntax better.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions