tags:

views:

31

answers:

2

I have an object, and before I serialize it to Json, I'd like to add a property to it. So my object will look like this:

    public class MySpecialObject {
       public int Id { get; set; }
       public string OneProperty { get; set; }
       public string ASecondProperty { get; set; }
    }

However, much later in the program I often want to add a property or two. This usually occurs in my controller, right before converting it to Json. I'd like to do something like this:

    ///Retrieve object from database
    var MySpecialObject = specialObjectRepository.Get(id);

    MySpecialObject.["DynamicProperty"] = "Dynamic Property!";

    ///Pretend I do Json serialization here
    return MySpecialObject;

That's obviously made up, but I hope what I'm trying to do is clear. In Javascript this is really easy to do since it is loosely typed. I thought with the dynamic keyword in C# 4.0 this would be possible, but it looks like that's not what it is for (though I could be completely missing the obvious). I guess I could create a class for these kinds of situations, but it'd be easier to just do it in one line. I know this sounds lazy, but it feels like what I'm trying to do should be possible.

+1  A: 

You want to inherit from ExpandoObject. It implements all the necessary plumping for a dynamic object.

shf301
A: 

You have to use the new ExpandoObject class:

    public class MySpecialObject:ExpandoObject {
       public int Id { get; set; }
       public string OneProperty { get; set; }
       public string ASecondProperty { get; set; }
    }

and, before serialization,simply write:

var MySpecialObject = specialObjectRepository.Get(id);

MySpecialObject.DynamicProperty = "Dynamic Property!";

You are not limited to add new properties, you can also add new methods and new events.

Andrea Parodi