Skip to content

Anonymous Type to interface convertion

Reflection Emit edited this page Mar 26, 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 CreateObject(object) extension (Cauldron.Activator) 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" }.CreateObject<ISampleInterface>();
        Console.WriteLine(sample.Name);
    }

What gets compiled:

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

    private static ISampleInterface<>anon_assign_2(<>f__AnonymousType0<int, string> <>f__AnonymousType)
    {
        return new <ISampleInterface> Cauldron_AnonymousType01
        {
            Index = <>f__AnonymousType.Index,
			Name = <>f__AnonymousType.Name

        } as ISampleInterface;
    }

The created type:

[EditorBrowsable(EditorBrowsableState.Never)]
[Serializable]
public sealed class <ISampleInterface>Cauldron_AnonymousType01 : ISampleInterface
{
	[DebuggerBrowsable(DebuggerBrowsableState.Never)]
	private int <Index>k_BackingField;

	[DebuggerBrowsable(DebuggerBrowsableState.Never)]
	private string <Name>k_BackingField;

	public int Index
	{
		[CompilerGenerated]
		get
		{
			return this.<Index>k_BackingField;
		}
		[CompilerGenerated]
		set
		{
			this.<Index>k_BackingField = value;
		}
	}

	public string Name
	{
		[CompilerGenerated]
		get
		{
			return this.<Name>k_BackingField;
		}
		[CompilerGenerated]
		set
		{
			this.<Name>k_BackingField = value;
		}
	}
}