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"]
androw.Field<string>("name")
? Of course, the second way cast value to some type, but is there another difference? - Which method is better to use?
It depends on your purpose but if you look at a definition of both that may tell you;
DataRow.Item Property (DataColumn)
row["name"]
DataRowExtensions.Field Method (DataRow, DataColumn)
row.Field<string>("name")
See Remarks section, main differences described there:
The last paragraph makes a point as I've often seen numbers stored as strings in database, therefore
varchar
toint
conversion would be required on data retrieval, so in this case using DataColumn is better, e.g.: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"]
returnsobject
,row.Field<string>("name")
returns aString
. We shouldn't be comparing apples and pears, hence you should be asking what's better:row["name"].ToString()
vsrow.Field<string>("name")
and the answer is: they're same.