DataRow field. The Field method on DataRow accesses a field. It is an extension method. It is found in the System.Data namespace. It is a generic method—this means it returns typed data. It makes field access easier.

Example. First, DataTable can be enumerated with the foreach-loop. Accessing the fields themselves is somewhat more complicated. The fields can have different types. The DataTable in the example has fields with types of int, string and DateTime.

Here: The example uses the foreach-loop. In the statement list it assigns variables to the results of the Field extension method.

Tip: The Field extension method receives a type parameter. It has several parameter list overloads.

The above program defines the Program class and two methods: the Main entry point, where control flow begins, and a GetTable static method. GetTable internally generates a DataTable instance with four columns and five rows.

The foreach-loop in the Main method loops over the DataTable with an iterator variable of type DataRow. The weight, name, code, and date variables are assigned to the results of the Field extension method with different parameters.

Field method parameters. There are two parameter lists on each method invocation to Field. The first parameter to the method is enclosed in the brackets. This is called a type parameter.

Tip: A type parameter indicates what type (such as int or string) you want the method to cast the result to.

Note: The second parameter list indicates the name or location of the field by its column identifier.

Internals. The DataRowExtensions class is an extension method class located in the System.Data.DataSetExtensions.dll file. When you use the methods such as Field in this class, the metadata loader will store this additional DLL in memory.

The Field extension method, as shown, will internally invoke a generic method that validates the parameter. It then uses a generic method to unbox the object inside the DataTable.

Performance: Because no copying of the actual data will take place, the Field extension method will have adequate performance.

Summary. We looked at the Field extension method found in the System.Data namespace and the DataSetExtensions class, using the C# language. This method allows you to use elegant syntax to access the fields in a DataRow by a column identifier.

Tip: Because this method will be found in all newer .NET installations, it is easy for you to maintain usage of this Field method.