Cast an Anonymous Types in Object and retrieve one Field

The options Joseph presents are good ones, but there is a horrible way you can do this. It’s somewhat fragile, as it relies on you specifying the anonymous type in exactly the same way in two places. Here we go:

public static T CastByExample<T>(object input, T example)
    return (T) input;


object item = ...; // However you get the value from the control

// Specify the "example" using the same property names, types and order
// as elsewhere.
var cast = CastByExample(item, new { Title = default(string),
                                     CategoryId = default(int) } );
var result = cast.Title;

EDIT: Further wrinkle – the two anonymous type creation expressions have to be in the same assembly (project). Sorry for forgetting to mention that before now.

Leave a Comment