Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class implementing interface [duplicate]

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
like image 266
flayn Avatar asked Jun 14 '10 13:06

flayn


People also ask

Can an anonymous class implement an interface?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

What happens if a class implement 2 interfaces having same method?

A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.

What is the purpose of anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


2 Answers

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.

like image 59
Lasse V. Karlsen Avatar answered Sep 23 '22 00:09

Lasse V. Karlsen


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>();
like image 40
jbtule Avatar answered Sep 23 '22 00:09

jbtule