Search code examples
c#interfaceanonymous-class

Anonymous class implementing interface


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

Solution

  • 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.