14

I have the following code inside a method:

 var list = new[]
  {
   new { Name = "Red", IsSelected = true },
   new { Name = "Green", IsSelected = false },
   new { Name = "Blue", IsSelected = false },
  };

I would like to call a function that requires a list of elements with each element implementing an interface (ISelectable). I know how this is done with normal classes, but in this case I am only trying to fill in some demo data.

Is it possible to create an anonymous class implementing an interface?

like this:

new { Name = "Red", IsSelected = true } : ISelectable
James McNellis
  • 348,265
  • 75
  • 913
  • 977
flayn
  • 5,272
  • 4
  • 48
  • 69

3 Answers3

12

No, this is not possible.

An anonymous type is meant to be a lightweight transport object internally. The instant you require more functionality than the little syntax provides, you must implement it as a normal named type.

Things like inheritance and interface implementations, attributes, methods, properties with code, etc. Not possible.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
12

The open source framework impromptu-interface will allow you to effectively do this with a lightweight proxy and the DLR.

new { Name = "Red", IsSelected = true}.ActLike<ISelectable>();
jbtule
  • 31,383
  • 12
  • 95
  • 128
  • 1
    This is amazing! I am playing around with it in LINQPad and it works brilliant so far. – flayn Apr 27 '11 at 21:51
1

Even if you could do this, you almost certainly would not want to since a method would know everything about the anonymous class (i.e. there is no encapsulation and also no benefit in accessing things indirectly).

On the other hand, I've thought about how such a feature might look (potentially useful if I want to pass an anonymously typed object to a method expecting a particular interface... or so I thought).

The most minimal syntax for an anonymous type that inherits an interface IFoo would be something like

new {IFoo.Bar = 2} // if IFoo.Bar is a property

or

new {IFoo.Bar() = () => do stuff} if IFoo.Bar is a method

But this is the simple case where IFoo only has one property or method. Generally, you would have to implement all of IFoo's members; including read/write properties and events which is currently not even possible on anonymously typed objects.

Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32
  • True, that would be neat. Maybe specify the interface of the anonymous class like this: new {IFoo.Bar = 2}:IFoo; – flayn Jun 17 '10 at 07:48