Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

DataSet vs. Typed DataSet

Many differences exist between DataSets and Typed DataSets, from syntax to performance issues. Here we'll discuss type safety and some additional benefits, such as how they behave to the compiler.

This code snippet shows how to use a DataSet:

.
.

String connectionString =
"server=localhost;Trusted_Connection=yes;database=Northwind";

SqlConnection conn = new SqlConnection(connectionString);

SqlDataAdapter EmployeesDA =
new SqlDataAdapter("SELECT * FROM EMPLOYEES;", conn);


DataSet ds = new DataSet();


EmployeesDA.Fill(ds, "Employees");

//Name of the table is misspelled to Employes
//instead Employees, which is wrong
Console.WriteLine(ds.Tables["Employes"].Rows[0]["FirstName"]);

//LastName contains one space at the end, which is wrong
Console.WriteLine(ds.Tables["Employees "].Rows[0]["LastName "]);


//this is wrong because ReportsTo must be an employeeID,
//an integer value
ds.Tables["Employees"].Rows[0]["ReportsTo"] = "Paul";

.
.

You can see in the code snippet that we use the table name and column name as Indexer on tables and rows. Finally, we set the ReportsTo column to a string instead of an integer value. When we run through the code, we don't get any compile time errors, but we get the mentioned errors (specified as comments) in the code at runtime. (You can try to fix them one by one and have a look at the already known errors.)

This code snippet shows how to use a Typed DataSet:

.
.

String connectionString =
"server=localhost;Trusted_Connection=yes;database=Northwind";

SqlConnection conn = new SqlConnection(connectionString);

SqlDataAdapter EmployeesDA =
new SqlDataAdapter("SELECT * FROM EMPLOYEES", conn);


//Creating an Instance of Typed DataSet "EmployeesTDS"
EmployeesTDS ds = new EmployeesTDS();


EmployeesDA.Fill(ds, "Employees");

Console.WriteLine(ds.Employees[0].FirstName);
Console.WriteLine(ds.Employees[0].LastName);


//this is wrong because ReportsTo must be an employeeID,
//an integer value
ds.Employee[0].ReportsTo = "Paul";

.
.

In this case, we access the table and columns with their names, but as part of the exposed functionality of Typed DataSet. A Typed DataSet exposes the table and columns with their names. If we make some errors in the code, we get these errors at compile time and can fix the error at the same time.

A comparison of these snippets shows us how easy it is to use Typed DataSets and illustrates their capability to expose the tables and columns as type-safe entities. At the same time, increased readability of programs gives quick access to the code's objective.

  • + Share This
  • 🔖 Save To Your Account