4
votes

I'm trying to implement a method that takes in a generic T and returns a list of T.

    public static List<T> GetMessages<T>(string query, int count, SqlConnection sqlconnection)
        where T : ITable, new()
    {
        List<T> messages = new List<T>();
        List<T> errorMessages = new List<T>();

        DataSet response = DBUtils.ExecuteQueryScriptWithConnection(query, sqlconnection);

        for (int i = 0; i < response.Tables[0].Rows.Count; ++i)
        {
            T message = new T();

            DataRow row = response.Tables[0].Rows[i];
            message.Id = Convert.ToInt32(row[0]);
            message.CreatedDate = Convert.ToDateTime(row[1]);                
        }

        return messages;
    }

But when I call it from another method, I get the error:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'CIHelpers.TableHelpers.GetMessages<T>(string, int, System.Data.SqlClient.SqlConnection)'

Code that I'm calling this from:

      List<T> messages = TableHelpers.GetMessages<T>(query, 1000, sqlconnection);

The class that implements ITable (type T that I'm passing is here.

public class MessageReceived : ITable
{
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }

    string query = String.Format(@"select Id, CreatedDate, from MessageReceived where createddate > '2013-04-18 00:00:00.0000000'");

    public MessageReceived()
    {

    }
}

What am I doing wrong?

1

1 Answers

6
votes

The T in the calling code needs to have the same constraints.

Otherwise, someone could call your wrapping function with a T that doesn't have a constructor.