I can’t cast one anonymous type to another. And I wonder why.
public static class Class1{
public static object GetFinance(Guid contractB2CId)
{
return new
{
Item1 = reader.ValueOrDefault<decimal>(0),
Item2 = reader.ValueOrDefault<decimal>(1),
Item3 = reader.ValueOrDefault<decimal>(2),
Item4 = reader.ValueOrDefault<decimal>(3),
Item5 = reader.ValueOrDefault<decimal>(4),
Item6 = reader.ValueOrDefault<decimal>(5)
};
}
object obj = GetFinance();
var financeInfo = obj.UnsafeCast(new
{
Item1 = default(decimal),
Item2 = default(decimal),
Item3 = default(decimal),
Item4 = default(decimal),
Item5 = default(decimal),
Item6 = default(decimal)
});
}
public static class Class2{
public static T UnsafeCast<T>(this object obj, T type)
{
return (T) obj;
}
}
The exception
Unable to cast object of type
‘<>f__AnonymousType16[System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal]'6[System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal]’.
to type
'<>f__AnonymousType0

UPDATE:
is there any way to avoid this exception except using Tuple<decimal.....> or using one assembly?
Anonymous types are bound to the assembly (technically, the module) that they are declared in. My guess is that this code is in different assemblies. Thus they are completely different types that happen to look similar.
Note that dynamically generated code (ASP.NET pages etc) will be in a different assembly.
By the way, this trick is called “cast by example”, and it works fine (just tested it) as long as the types are in the same assembly.
Here it is working, because it is all in one assembly: