Q. What's the difference between typed dataset and untyped dataset? When do you use which?

Asked by reader. Answered by the Wonk on November 5, 2002

A.

An "untyped" dataset is an instance of the DataSet class from the System.Data namespace. It’s called “untyped” because all columns are provided as the base System.Object type (“object” in C# and “Object” in VB.NET) and must be coerced to the appropriate type, e.g.

void Form1_Load(object sender, EventArgs e) {
  DataSet ds = new DataSet();
  sqlDataAdapter1.Fill(ds);
  foreach( DataRow row in ds.Tables[0].Rows ) {
    string fname = (string)row["au_fname"];
    bool contract = (bool)row["contract"];
    string item =
      string.Format("{0} has a contract: {1}", fname, contract);
    listBox1.Items.Add(item);
  }
}

The problem, of course, is that it’s a pain to get the coercion code is tedious to write and easy to get wrong. A type-safe dataset, on the other hand, allows you to write the following code:

void Form1_Load(object sender, EventArgs e) {
  AuthorsDataSet ds = new AuthorsDataSet();
  sqlDataAdapter1.Fill(ds);
  foreach( AuthorsDataSet.authorsRow row in ds.authors.Rows ) {
    string fname = row.au_fname;
    bool contract = row.contract;
    string item =
      string.Format("{0} has a contract: {1}", fname, contract);
    listBox1.Items.Add(item);
  }
}

In this case, notice that we have a new type, AuthorsDataSet. It derives from the DataSet base type and provides type-safe access to each column in each row via the authorsRow nested type and the authors property on the filled AuthorsDataSet. Now we can simply access the columns as if they were fields without any type coercion code.

Feedback Responses

Paul Janssen asked: "Do typed datasets provide methods for finding rows in a datatable?  What other kinds of functionality do typed datasets provide?"

Typed data sets provide three features that aren't part of the base DataSet class. One, they provide a designer surface for laying out relationships and constraints. Two, they provide type-checked operations, i.e. retrieval, inserts and updates. Three, they provide a special constructor to add serialization support to your typed data set. All of the rest of the functionality, e.g. finding rows, comes from the DataSet and related classes themselves.

However, the typed data set does provide a wrapper for finding a row by a table's primary key:

void findButton_Click(object sender, System.EventArgs e) {

  // Find by primary key

  SubscribersDataSet.SubscribersRow row =

    subscribersDataSet1.Subscribers.FindByID(int.Parse(idTextBox.Text));

  MessageBox.Show(row.name, "Subscriber");

}

 

Feedback

I have feedback on this Ask The Wonk answer