Do you know property names at compile time? Because you can do this:
public static T CastByExample<T>(object o, T example) { return (T)o; } public static object MyMethod(object obj) { var example = new { FirstProperty = "abcd", SecondProperty = 100 }; var casted = CastByExample(obj, example); return new { FirstProperty = casted.FirstProperty, SecondProperty = casted.SecondProperty, AddedProperty = true }; }
Then:
var extendedObject = MyMethod( new { FirstProperty = "abcd", SecondProperty = 100 } ); var casted = CastByExample( extendedObject, new { FirstProperty = "abcd", SecondProperty = 100, AddedProperty = true } ); Console.WriteLine(xyz.AddedProperty);
Note that this very much depends on the fact that two anonymous types in the same assembly with properties that have the same name of the same type in the same order have the same type.
But, if you are going to do this, why not just create specific types?
Output:
True
jason source share