I have the following simple function:
private static Nullable<T> CastValue<T>(object val)
where T : struct
{
if (!(val is DBNull))
{
return (T) val;
}
return null;
}
I would like to call it while iterating over rows/columns of a data table like this:
var table = CreateTable();
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Type type = column.DataType;
CastValue<type>(row[column]);
}
}
However, I am getting the following error:
The type or namespace name ‘type’ could not be found (are you missing
a using directive or an assembly reference?)
Is there a way to call a generic function with a generic parameter that is determined at run time?
You can’t1 because generic arguments are resolved at compile-time, while the column’s type will only be known at run-time.
Since you’re not doing anything with the result of
CastValueit’s unclear what you’re trying to accomplish, but a cast should be unnecessary sincerow[column]should already be an instance of the column’s data type.1You can with reflection but I don’t see how it helps your situation.