Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast anonymous type to an interface?

Tags:

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:

  • http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.internalsvisibletoattribute.aspx (Jon's suggestion)
like image 330
sgtz Avatar asked Feb 12 '12 14:02

sgtz


People also ask

What is casting to an interface?

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.

Do anonymous types work with Linq?

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.

Can you instantiate an interface C#?

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.


2 Answers

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>(); 
like image 105
Ani Avatar answered Sep 19 '22 14:09

Ani


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.

like image 40
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet