I have class method:
public object MyMethod(object obj)
{
// I want to add some new properties example "AddedProperty = true"
// What must be here?
// ...
return extendedObject;
}
And:
var extendedObject = this.MyMethod( new {
FirstProperty = "abcd",
SecondProperty = 100
});
Now the extendedObject has new properties. Help please.
You can't do that.
If you want a dynamic type that you can add members to at runtime then you could use an ExpandoObject
.
Represents an object whose members can be dynamically added and removed at run time.
This requires .NET 4.0 or newer.
You can use a Dictionary (property, value) or if you are using c# 4.0 you can use the new dynamic object (ExpandoObject).
http://msdn.microsoft.com/en-us/library/dd264736.aspx
Do you know at compile-time the names of the properties? 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 relies very heavily on the fact that two anonymous types in the same assembly with properties having the same name of the same type in the same order are of the same type.
But, if you're going to do this, why not just make concrete types?
Output:
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With