Any chance to cast this to the anonymous type?
Although you can do that but it is highly unreliable. Because whenever you will change your creation of anonymous type your code will suddenly break on other places without a trace.
You can read all the downfalls of casting anonymous types in blog by Jon Skeet here. Also worth reading are the comments by Marc Gravel.
Example of breaking change as discussed in the above blog.
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
All good. Now what if you suddenly realise that you need to change CreateCheeseCake to something like this
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate", Base = "Biscuit" };
}
Then what will happen to your this line
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
it won't work anymore.