.NET: Passing a DataSet through the ExtendedProperties of another DataSet
Sometimes you find the need to pass more than one DataSet as the result of a routine/function. Although you can use reference parameters for doing so, there's another approach.
You can pass additional DataSets by adding them to the ExtendedProperties property of the "main" DataSet. ExtendedProperties is defined as being of type PropertyCollection, which inherits from the Hashtable type, so its limit depends on the amount of memory that the host machine has.
A limitation that becomes apparent when using .NET remoting is that the values stored in the ExtendedProperties should be of type string in order to be persistent when it crosses the application domains between the server and the client. With this limitation in mind, the steps are roughly as follows:
1. Convert the "additional" DataSet to string.
2. Store the result of step 1 in the ExtendedProperties of the "main" DataSet.
3. Pass/return the "main" DataSet to the calling process.
4. Convert the string representation of the "additional" DataSet back.
The DataSet class has a GetXml method that returns the XML representation of the DataSet.
Steps 2 & 3:
The DataSet class has a ReadXml method for initalizing a DataSet based on XML.
Combining all the information, the code can look something like this:
==== START OF SAMPLE CODE ====
// SAMPLE FUNCTION (SampleFunction())
// Populate the DataSets here
dsSubAsString = dsSub.GetXml();
// Pass dsMain to calling routine/function
// CALLING FUNCTION
// Call function to retrieve the DataSets
// and convert dsSub
dsMainReturn = SampleFunction();
dsSubReturn = new DataSet();
string dsSubReturnAsString = (string) dsMainReturn.ExtendedProperties["dsSub"];
using (System.IO.StringReader sr = new StringReader(dsSubReturnAsString))
// Use dsSubReturn as required
==== END OF SAMPLE CODE ====
And there you have it. Taking it a step further, the code for conversion from XML/string to DataSet can be wrapped as a function in a helper class, so as not to affect programmer productivity. :)