I have the following code, where i am trying to create a generic collection for the objects in my DAL (just an exercise, not actually production code). My problem is that i want to use the type passed in's Read method (which is part of an interface that the classes implement).
I cannot create a new T
so i dont have an instance of the object to work with, and i cant declare it as the base type, as i need the read method specified by the child of the base object.
Is this actually possible or am i barking up the wrong tree?
public class ItemDictionary<T> where T : ILoadable, DataItem
{
public void Load()
{
using (IDataReader reader = SqlHelper.ExecuteReader(_connection, CommandType.StoredProcedure, _proc)) {
Read(reader);
}
}
bool Read(IDataReader reader)
{
while (reader.Read)
{
T item = default(T); //Here be the problem
if (item.Read(reader))
{
this.Add(item.Guid, item);
}
}
return true;
}
}
public class ExampleObject : DataItem, ILoadable
{
bool Read(IDataReader reader)
{
_var1 = reader.getString(0);
_var2 = reader.getString(1);
_var3 = reader.getString(2);
return true;
}
}