difference between getting value from DataRow

nirmus picture nirmus · Aug 18, 2011 · Viewed 18.1k times · Source

Sample code:

    DataTable table = new DataTable();

    // ...
    // insert column to table

    table.Columns.Add("name");

    // ...
    // insert value to table

    foreach (DataRow row in table.Rows) {
         row["name"];
         row.Field<string>("name");     
    }

My question is:

  • Is there a difference between using row["name"] and row.Field<string>("name")? Of course, the second way cast value to some type, but is there another difference?
  • Which method is better to use?

Answer

Иван Грозный picture Иван Грозный · Aug 18, 2011

See Remarks section, main differences described there:

The DataSet class represents null values with the Value instance of the DBNull class. A Language-Integrated Query (LINQ) expression that accessed a column with a null value would generate a InvalidCastException at run time. Additionally, DataSet does not support nullable types. The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is Value, the returned nullable type will have a value of null.

If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value.

The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.

The last paragraph makes a point as I've often seen numbers stored as strings in database, therefore varchar to int conversion would be required on data retrieval, so in this case using DataColumn is better, e.g.:

int test = row.Field<int>("Test"); // InvalidCastException
int test = Convert.ToInt32(row["Test"]); // Works like a charm

DataRowExtensions.Field<T> Method (DataRow, String) first appeared in .NET 3.5 and it "provides strongly-typed access to each of the column values in the specified row. The Field method also supports nullable types."

Afaik, row["name"] returns object, row.Field<string>("name") returns a String. We shouldn't be comparing apples and pears, hence you should be asking what's better:

row["name"].ToString() vs row.Field<string>("name") and the answer is: they're same.