Click or drag to resize

ExtensionsInterceptionCreateTypeT Method

Creates a new Type that implements the properties of an interface defined by T and copies all value of anon to the new object.

Namespace:  Cauldron.Interception
Assembly:  Cauldron.Interception (in Cauldron.Interception.dll) Version: 1.0.0
Syntax
public static T CreateType<T>(
	this Object anon
)
where T : class

Parameters

anon
Type: SystemObject
The anonymous object

Type Parameters

T
The type of interface to implement

Return Value

Type: T
A new object implementing the interface defined by T

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type Object. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Examples
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. This also can be handy in situations where it is an overkill to create a new class. Lazy programmers will love this. To achieve this, a new type is weaved into your assembly.

The following examples illustrates how the weaver modifies your code.

Your code:

private static void Main(string[] args)
{
    var sample = new { Index = 0, Name = "Hello" }.CreateType<ISampleInterface>();
    Console.WriteLine(sample.Name);
}
Your code will look like this after the weaver's modification:
private static void Main(string[] args)
{
    var sample = Assign(new
    {
        Index = 0,
        Name = "Hello"
    });
    Console.WriteLine(sample.Name);
}
The weaver creates a new type that implements the ISampleInterface.
[EditorBrowsable(EditorBrowsableState.Never)]
[Serializable]
public sealed class SampleInterfaceCauldronAnonymousType : ISampleInterface
{
    public int Index { get; set; }
    public string Name { get; set; }
}
The weaver also adds a new method that maps the values from the anonymous type to the SampleInterfaceCauldronAnonymousType.
[EditorBrowsable(EditorBrowsableState.Never)]
private static SampleInterfaceCauldronAnonymousType Assign(AnonymousType<int, string> anonymousType)
{
    return new SampleInterfaceCauldronAnonymousType
    {
        Index = anonymousType.Index,
        Name = anonymousType.Name
    };
}
See Also