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
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
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.
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.
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With