Reputation: 846
The snippet below works just fine for a given method but I want to do the same during class construction. How to do it?
public static DataTable ToDataTable<T>(IList<T> data)
Want something like this...but the constructor doesn't like the <T>(IList<T>
part.
public class DTloader
{
PropertyDescriptorCollection props;
DataTable dataTable = new DataTable();
public DTloader<T>(IList<T> data)
{
props = TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
}
.......
Upvotes: 2
Views: 1054
Reputation: 1992
Besides the answers given, If you want to have a non generic DTLoader you can create an abstract DTLoader and make the generic one inherit from it
abstract class DTLoader
{
//..
}
class DTLoader<T> : DTLoader
{
public DTloader(IList<T> data)
{
//...
}
}
This would actually give you the feel you seem to want - Have just the constructor use a generic type.
Upvotes: 1
Reputation: 218808
At that point the class itself would need to be generic. Something like this:
public class DTloader<T>
{
//...
public DTloader(IList<T> data)
{
//...
}
}
The constructor would know at compile-time what T
is because the declaration of the class instance would specify it (or be able to infer it).
Upvotes: 6