Anonymous Interface Implementations

Imagine you have an interface that has no methods - only properties:

public interface IFoo
    public int Id { get; }
    public string Name { get; }

Now imagine you have a method you need to call that takes an IFoo parameter. You don't, however, have a class handy that implements IFoo. You just want to pass some data in there on the fly.

Right now in C# you'd have to define a "fake" IFoo implementation class and instantiate one of those. I'd love to be able to do away with that step, and have the compiler do it for me. That means I could do this:

IFoo foo = new { Id = 1, Name = "My fake IFoo" };

Or it might look something like this:

var foo = new IFoo { Id = 1, Name = "My fake IFoo" };

This would save a lot of ceremony when all you need is a quick-and-dirty implementation of an interface. Obviously it wouldn't work with interfaces that have methods in their definition, but the compiler could sort that out and error if that were the case.

c# wishlist .net language
Posted by: Matt Hamilton
Last revised: 24 Apr, 2017 07:02 PM History


10 Dec, 2010 04:22 AM

For the record, I did write sample code on how to do this: ;)

07 Jan, 2011 07:45 AM

That's how it's done in the land of Java...of course on the downside, they don't have Events. I remember the fun of implementing a button click handler in AWT back when I was doing Java.

No new comments are allowed on this post.