A few days ago I blogged about a tiny fun project of mine, where I added dynamic type support to the DataTable and DataRow classes.
This was fun, and the code works as intended, but it has a two shortcomings: There was a bug preventing you from setting values of regular properties on the DynamicDataRow type, and you couldn't add new columns using dynamic properties.
Naturally, I had to fix this, so here it is: The DynamicDataTable v2!
What is new?
Most of the code is the same as last time, but this time the useage is even simpler. You just create a new DynamicDataTable object, add a new row using the NewRow method and assign values to the properties you need. Look at this:
// Create a DataTable
var tb = new DynamicDataTable();
// Row using dynamic syntax
dynamic row = tb.NewRow();
row.aa = "Dynamic here!";
row.bb = 44;
row.cc = DateTime.Now;
tb.Rows.Add(row);
// Access column values using property accessors instead of using the indexer
Console.WriteLine("AA: " + row.aa);
Console.WriteLine("BB: " + row.bb);
Console.WriteLine("CC: " + row.cc);
If you compare this with the previous version you see that I have removed the column definitions. Now when the DynamicDataRow intercepts a call to a property set for a property that doesn't exist it will check its DataTable to see if there is a column with that name. If it can't find a column with that name it will add a new column and set its datatype to the type of the assigned value. In the above example our table ends up with three columns: "aa" of type String, "bb" of type Int32 and "cc" of type DateTime. Later you can access the DataTable as a regular table if you want.
The updated source code
I have uploaded an updated version of the source code if you are interested: DynamicDataTable.zip (4.57 kb)

1037b5af-8f32-4969-ab18-6b9e8b7a7df6|1|5.0
.NET
.net