This doesn't seem to be possible? So what is the best work-around? Expando / dynamic?
public interface ICoOrd { int x { get; set; } int y { get; set; } }
...
ICoOrd a = new {x = 44, y = 55};
ref:
A type cast—or simply a cast— is an explicit indication to convert a value from one data type to another compatible data type. A Java interface contains publicly defined constants and the headers of public methods that a class can define.
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces.
The best "workaround" is to create and use a normal, "named" type that implements the interface.
But if you insist that an anonymous type be used, consider using a dynamic interface proxy framework like ImpromptuInterface
.
var myInterface = new { x = 44, y = 55 }.ActLike<ICoOrd>();
No, anonymous types never implement interfaces. dynamic
wouldn't let you cast to the interface either, but would let you just access the two properties. Note that anonymous types are internal
, so if you want to use them across assemblies using dynamic
, you'll need to use InternalsVisibleTo
.
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