Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an object of the anonymous class

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.

like image 843
Jean Louis Avatar asked Dec 21 '10 19:12

Jean Louis


3 Answers

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.

like image 158
Mark Byers Avatar answered Oct 21 '22 20:10

Mark Byers


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

like image 22
Jaime Avatar answered Oct 21 '22 19:10

Jaime


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
like image 38
jason Avatar answered Oct 21 '22 20:10

jason