We help IT Professionals succeed at work.

Dynamic Cast in C#

Kyle Abrahams
Medium Priority
Last Modified: 2010-05-18
Hi All,

I have a dynamic SQL query which can return a variable number of columns.

What I'm trying to do is dynamically create the datatable based on the datareader.  
source is an actual SqlDataReader so that cast is valid (in this case it can be other things but for right now I'm just concentrating on this case).

// create datatable.
  DataTable dt = new DataTable();

// add the columns based on the number of columns in the datareader
                for (int i = 0; i < ((SqlDataReader)source).FieldCount; i++)
                    dt.Columns.Add(i.ToString(), ((SqlDataReader)source)[i].GetType());

                while (((SqlDataReader)source).Read())
//create new datarow
                    DataRow r = dt.NewRow();

//trying to assign the datareader value to the row value.  This is where the dynamic cast comes in.
//I won't know the actual type until runtime, as I said values and columns can change.
                    for (int j = 0; j < dt.Columns.Count; j++)
                      r[j] =  (Type.GetType((((SqlDataReader)source)[j].GetType().ToString())) ((SqlDataReader)source)[j] );

//can now work on datatable.
Watch Question

Is there any reason not to load directly into a data table instead of a datareader??
Kyle AbrahamsSenior .Net Developer


how so?
Well without seeing the code that loads into the SqlDataReader I can't give you specifics, but something like:

SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");

SqlCommand selectCMD = new SqlCommand("SELECT CustomerID, CompanyName FROM Customers", nwindConn);
selectCMD.CommandTimeout = 30;

SqlDataAdapter custDA = new SqlDataAdapter();
custDA.SelectCommand = selectCMD;


DataSet custDS = new DataSet();
custDA.Fill(custDS, "Customers");


Then you now have


and that is how to access your data table.

Now there are more .NET 2 methods to do this and even better is using a single line or two of code using the Enterprise Library.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.