ExpandoObject – add properties dynamically

Posted on

ExpandoObject class allows to create an object of dynamic type. This dynamic type object allows to attach properties to it at runtime. While working on a project recently, I had to create a data service which builds response for a data request without knowing the schema and source of data. The request contains following information Request.TableName : “SegmentTable” Request.RequiredFields: [“SegmentKey”, “SegmentIndex”, “Attribute1”, “Attribute2”, “Attribute4”] SegmentTable looks like something SegmentID SegmentKey SegmentIndex Attribute1 Attribute2 Attribute3 Attribute4 ……. Data service builds a query like [SELECT * from {SegmentTable}] and then creates a collection of ExpandoObjects  against each row returned against this query. This code snippet shows how an ExpandoObject is created from a datatable row.

ExpandoObject uses dictionary underneath to achieve this but for the users its very seamless. We can attach the properties directly to the object as well. In this case since the names of those properties were also coming from database/request so we had to type cast […]