[ACCEPTED]-cast anonymous type to an interface?-anonymous-types

Accepted answer
Score: 31

The best "workaround" is to create 5 and use a normal, "named" type 4 that implements the interface.

But if you 3 insist that an anonymous type be used, consider 2 using a dynamic interface proxy framework 1 like ImpromptuInterface.

 var myInterface =  new { x = 44, y = 55 }.ActLike<ICoOrd>();
Score: 9

No, anonymous types never implement interfaces. dynamic wouldn't 5 let you cast to the interface either, but 4 would let you just access the two properties. Note 3 that anonymous types are internal, so if you want 2 to use them across assemblies using dynamic, you'll 1 need to use InternalsVisibleTo.

Score: 4

I know this is an old question and answers 12 but I stumbled on this on this looking to 11 do exactly the same thing for some unit 10 tests. I then occurred to me that I am already 9 doing something like this using Moq (facepalm).

I 8 do like the other suggestion for ImpromptuInterface 7 but I am already using Moq and feel like 6 it having a larger following (that is opinion 5 and not fact) will be more stable and supported 4 longer.

so for this case would be something 3 like

public interface ICoOrd
    int X { get; set; }
    int Y { get; set; }

public class Sample

    public void Test()
        var aCord = new Mock<ICoOrd>();
        aCord.SetupGet(c => c.X).Returns(44);
        aCord.SetupGet(c => c.Y).Returns(55);

        var a = aCord.Object;

EDIT: just adding another way to mock the 2 cord, started doing it this way and like 1 it a little better.

public void AnotherTest()
    var aCord = Mock.Of<ICoOrd>(c => c.X == 44 && c.Y == 55);
    //do stuff with aCord

More Related questions