laconicdev
laconicdev

Reputation: 6440

Specifying type for generic function

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?

Upvotes: 0

Views: 80

Answers (2)

D Stanley
D Stanley

Reputation: 152556

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 CastValue it's unclear what you're trying to accomplish, but a cast should be unnecessary since row[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.

Upvotes: 1

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

I think that you need to make a none generic version of the function. If you think about it, if you pass in a wrong type, it will endup with a runtime error, so you don't get anything by doing it generic.

Upvotes: 1

Related Questions