views:

219

answers:

2

Hi, I am trying to create a method that takes a DataTable or a DataRowCollection and converts it to an array of a generic type. Something like this:

    public static T[] ConvertToArray<T>(DataTable dataTable)
    {
        List<T> result = new List<T>();

        foreach (DataRow dataRow in dataTable.Rows)
            result.Add((T)dataRow);

        return result.ToArray();
    }

The problem is this line

result.Add((T)dataRow);

which gives Cannot convert System.Data.DataRow to T.

If I do the same thing without using a generic type, and make sure the class of the objects have a defined custom conversion operator, the code works fine.

So the question is now, how do I pull this of using generics?

+2  A: 

You could use an object that provides the conversion on a DataRow to your type :

public interface IDataRowConverter<T>
{
    T Convert(DataRow row);
}

Provide your custom converter to your function :

public static T[] ConvertToArray<T>(DataTable dataTable, IDataRowConverter<T> converter)
{
    List<T> result = new List<T>();

    foreach (DataRow dataRow in dataTable.Rows)
        result.Add(converter.Convert(dataRow));

    return result.ToArray();
}

Then, implement the interface for your needed type :

public class MyObjectDataRowConverter : IDataRowConverter<MyObject>
{
    public MyObject Convert(DataRow row)
    {
        MyObject myObject = new MyObject();

        // Initialize object using the row instance

        return myObject;
    }
}

You can then call your function using this code :

MyObject[] objectArray = 
    ConvertToArray<MyObject>(datatable, new MyObjectDataRowConverter());
Thibault Falise
Can I use the implicit conversion methods I define on the classes I want to be able to convert? They look like this:public static implicit operator Posting(DataRow dataRow) { // something that retusn a Posting object }
Olle
If you want to use a generic implementation, any operation you want to use must be defined on the generic type.You cannot use the operator in your function when working with the generic implementation as .net does not allow operator constraints.However, using the described method, you can use the operator when implementing your Converter class.
Thibault Falise
Ok, many thanks! I will have to do it that way then. Thanks!
Olle
A: 

What kind of will be?

Kate