Skip to content

Anonymous Type to interface convertion

Reflection Emit edited this page Jul 25, 2017 · 7 revisions

In some special cases (e.g. unit tests) it may be required to convert an anonymous type to a type that implements a certain interface. The CreateType(object) extension (Cauldron.Interception Fody addins) offers this functionality.
To achieve this a new type is weaved into your assembly.

Example:

    private static void Main(string[] args)
    {
        var sample = new { Index = 0, Name = "Hello" }.CreateType<ISampleInterface>();
        Console.WriteLine(sample.Name);
    }

What gets compiled:

    private static void Main(string[] args)
    {
        var sample = AnonAssign(new
        {
            Index = 0,
            Name = "Hello"
        });
        Console.WriteLine(sample.Name);
    }
    
    [EditorBrowsable(EditorBrowsableState.Never)]
    private static SampleInterfaceCauldronAnonymousType AnonAssign(AnonymousType<int, string> anonymousType)
    {
        return new SampleInterfaceCauldronAnonymousType
        {
            Index = anonymousType.Index,
            Name = anonymousType.Name
        };
    }

The created type:

[EditorBrowsable(EditorBrowsableState.Never)]
[Serializable]
public sealed class SampleInterfaceCauldronAnonymousType : ISampleInterface
{
	public int Index { get; set; }
	public string Name { get; set; }
}