-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
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.