How to extend an anonymous class object

I have a 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 }); 

The extendedObject now has new properties. Help me please.

+4
source share
3 answers

You cannot do this.

If you need a dynamic type to which you can add participants at runtime, you can use ExpandoObject .

Represents an object whose members can be dynamically added and deleted at runtime.

This requires .NET 4.0 or later.

+11
source

You can use a dictionary (property, value), or if you use C # 4.0, you can use a new dynamic object (ExpandoObject).

http://msdn.microsoft.com/en-us/library/dd264736.aspx

+1
source

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 
+1
source

Source: https://habr.com/ru/post/1332949/


All Articles