Dynamic Cast in C#

Posted on 2006-03-22
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.
Question by:Kyle Abrahams
    LVL 35

    Expert Comment

    Is there any reason not to load directly into a data table instead of a datareader??
    LVL 39

    Author Comment

    by:Kyle Abrahams
    how so?
    LVL 35

    Accepted Solution

    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.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Suggested Solutions

    Title # Comments Views Activity
    WiX Installer 2 37
    sort multidimensional array in c# 2 31
    Path of Workbook 3 30
    Any reason why this might be bad? 7 27
    Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
    Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now