6

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.

Jean Louis
  • 1,485
  • 8
  • 18
  • 33

3 Answers3

13

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

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

Jaime
  • 6,736
  • 1
  • 26
  • 42
1

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
jason
  • 236,483
  • 35
  • 423
  • 525