SyntaxHighlighter

Wednesday, August 13, 2008

Constraint cannot be special class 'object'

I was busy creating a generic method to convert a List to a DataTable when I received the error:
Constraint cannot be special class 'object'
on this statement:
public DataTable ListToDataTable(IList list) where T : Object

Blegh... why would this be? Anyhow, I did a workaround by changing the statement to the following:
public DataTable ListToDataTable(T list) where T : IList

A bit annoying, since now one has to send a List and can't simply pass a List.

Another workaround is to use a blank interface, with the statement as:
public DataTable ListToDataTable(IList list) where T : IBlank

Now one can send List if MyClass 'implements' the IBlank interface.

I'm not really too happy with any of these workarounds. I see no reason why the Object class is "too special" to be used as a generic placeholder.

Oh, and merely for interest sake. Here is the generic List to DataTable converter method:
public DataTable ListToDataTable(List list) where T : IBlank
{
DataTable dataTable = new DataTable();

Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();

// Create the columns
foreach (PropertyInfo property in properties)
dataTable.Columns.Add(property.Name, property.PropertyType);

// Populate the rows
foreach (T obj in list)
{
DataRow newRow = dataTable.NewRow();

foreach (PropertyInfo property in properties)
newRow[property.Name] = property.GetValue(obj, null);

dataTable.Rows.Add(newRow);
}

return dataTable;
}

3 comments:

Stephen Cleary, Nito Programs said...

I think what you want is "where T : class" (although this would also compile without any constraint at all)

LittleTijn said...

Another way to solve this, is to use the new() constraint.

Example:

public DataTable ListToDataTable(T list) where T : new()

This way T must be a object with a parameterless constructor!

Alex Quick said...

Does where T : class get us anywhere?