confused_programmer
confused_programmer

Reputation: 103

Is it possible to cast a generic DataRow, which is based off of a typed DataRow, back to typed datarow using its attributes?

I have an Oracle database full of similar tables (many common columns) which I use a dataSet to work with. Each table has a class to access the database including an extension method updateInDatabase()

I would like to create some methods which modify the common columns of the DataRows and return a generic DataRow. Is it possible to convert it back to a typed DataRow based on it's attibutes? I can see that the DataRow still holds information related to it's original type and table.

I'm guessing it would look something like this:

var typedDataRow = (genericDataRow.GetType())genericDataRow;

I am hoping to get the same result as the following but without knowing the type at runtime:

TypedDataRow typedDataRow = (TypedDataRow)genericDataRow;

When I try the above, the error is '; expected'

Upvotes: 1

Views: 392

Answers (1)

OAkbas
OAkbas

Reputation: 21

An extension method like this will be helpful

    public static T ConvertRow<T>(this DataRow row)
    {
        var obj = Convert.ChangeType(row, typeof(T));
        return (T)obj;                
    }

you can use it anywhere you want;

    TypedDataRow typedDataRow = genericDataRow<TypedDataRow>.ConvertRow()

Upvotes: 1

Related Questions