views:

111

answers:

4

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
+1  A: 

I think, this is currently not possible.

Beknägge
-1: how is this helpful?
ANeves
A: 

No you can't.

In order to implement an interface, you would have to provide the corresponding method definitions. An Anonymous class can ONLY have public read-only properties; which means it can't have a method....

which means it can't implement any interfaces.

And from MS:

Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

Chris Lively
Sure about the "ONLY private fields". I think they are all public.
Flo
And they aren't fields, they're properties.
Lasse V. Karlsen
@Flo/Lasse: I stand corrected. I had quoted a bad web page. Silly me for not thinking.
Chris Lively
+8  A: 

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
A: 

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
True, that would be neat. Maybe specify the interface of the anonymous class like this:new {IFoo.Bar = 2}:IFoo;
Flo