The var is all about type inference, it’s important to remember this is still static typing. The var keyword informs the compiler that it should try and infer the type of variable; if it can not do this a compile error is generated. One very important aspect of the var keyword is that it can only be used with local variables, and even then are a few cases that are not allowed.
In this below example I used this var keyword instead of specific datatype declared.
public static DataTable ConvertDataViewToDataTable(DataView dataView)
{
// check whether passed dataview is null or not.
if (null == dataView)
{
throw new ArgumentNullException("DataView", "Null or Invalid DataView");
}
// Create table structure from dataview by using Clone().
var newDataTable = dataView.Table.Clone();
var index = 0;
// Create the same number of column.
var strColNames = new string[newDataTable.Columns.Count];
// Add the column names to datatable.
foreach (DataColumn col in newDataTable.Columns)
{
strColNames[index++] = col.ColumnName;
}
// Fetch all rows from dataview to Enumerator.
var viewEnumerator = dataView.GetEnumerator();
while (viewEnumerator.MoveNext())
{
var dataRowView = (DataRowView)viewEnumerator.Current;
// Create new datarow and fill the values init from dataview.
var dataRow = newDataTable.NewRow();
foreach (var strName in strColNames)
{
dataRow[strName] = dataRowView[strName];
}
// Add the new datarow to the datatable.
newDataTable.Rows.Add(dataRow);
} // while loop end
// Return the created datatable.
return newDataTable;
}
Happy codings!!!