Error: "T" must not be an abstract type with an open constructor without parameters in order to use it as a parameter of "T",

I am trying to implement a method that takes a generic T and returns a list 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 this from another method, I get an error:

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

The code I call from this:

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

A class that implements ITable (the type T I pass in 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?

+4
source share
1 answer

T calling code must have the same restrictions.

Otherwise, someone might call your wrapping function with T , which does not have a constructor.

+5
source

All Articles