I’ve been trying to create a simple base class that encapsulates some of my conventions for database access. I generally create a sproc named ‘products_retrieve_product’ to select a product based on productID. I would like the method ‘Retrieve’ in the base class to return the type that the derived class supplies in it’s definition. Is what I’m trying to accomplish possible with Generics?
public class MyBaseClass <T> { private string _className; public MyBaseClass () { _className = this.GetType().Name; } public virtual T Retrieve(int ID) { Database db = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = db.GetStoredProcCommand(String.Format('{0}s_Retrieve_{0}', _className)); db.AddInParameter(dbCommand, String.Format('@{0}ID', _className), DbType.Int32, ID); using (IDataReader dr = db.ExecuteReader(dbCommand)) { if (dr.Read()) { BOLoader.LoadDataToProps(this, dr); } } return (T)this; } }
I think that you want to do something like this:
When you run this program, the type name of Foo is printed on the command line. Obviously this is a contrived example, but maybe you can do something more useful when loading from a database in
MyBaseClass.Retrieve().The key is to add a constraint on T so that it must be an instance of the class itself. This way you can specify the subclass as the generic type when subclassing
MyBaseClass<T>.I’m not entirely sure if this is a good idea or not, but it looks like it can be done.