I am wondering what it would take to make something like this work:
using System;
class Program
{
static void Main()
{
var f = new IFoo {
There would be a few issues with overloaded members, indexers, and explicit interface implementations.
However, you could probably define the syntax in a way that allows you to resolve those problems.
Interestingly, you can get pretty close to what you want with C# 3.0 by writing a library. Basically, you could do this:
Create
(
new
{
Foo = "foo",
Print = (Action)(() => Console.WriteLine(Foo))
}
);
Which is pretty close to what you want. The primary differences are a call to "Create" instead of the "new" keyword and the fact that you need to specify a delegate type.
The declaration of "Create" would look like this:
T Create (object o)
{
//...
}
It would then use Reflection.Emit to generate an interface implementation dynamically at runtime.
This syntax, however, does have problems with explicit interface implementations and overloaded members, that you couldn't resolve without changing the compiler.
An alternative would be to use a collection initializer rather than an anonymous type. That would look like this:
Create
{
new Members
{
{"Print", ((IFoo @this)=>Console.WriteLine(Foo))},
{"Foo", "foo"}
}
}
That would enable you to:
You would need to do a few things to implement this: