I have throughout my application many methods where I load collections. They all (actually most with a couple of differentials) follow the following pattern:
public BaseCollection<ObjectType1> LoadObjectType1(EventHandler handleEvent)
{
var myQuery = ObjectType1.Load(MyServiceContext);
return new DataManager<ObjectType1>().GetData(myQuery , handleEvent, MyServiceContextt);
}
public BaseCollection<ObjectType2> LoadObjectType2(EventHandler handleEvent)
{
var myQuery = ObjectType2.Load(MyServiceContext);
return new DataManager<ObjectType2>().GetData(myQuery , handleEvent, MyServiceContextt);
}
public BaseCollection<ObjectType3> LoadObjectType3(EventHandler handleEvent)
{
var query = ObjectType3.Load(MyServiceContext);
return new DataManager<ObjectType3>().GetData(query, handleEvent, MyServiceContextt);
}
Where ObjectType# are my business objects, e.g. Employee, Department, etc.
I would like to convert these to harness Generics.
Any advice will be greatly appreciated.
You can always create version of these functions that take a generic argument themselves. However, since there is no argument that can allow the compiler to infer the type of the generic argument, you will always have to supply it in the call.
The main issue, is that you’re using a static
Loadmethod that is implemented on each object type. You would have to pass this in to the call as a delegate:When calling these version, you would have to specify the type
T, as well as pass in a delegate that will return the query object you use to load your data (since it’s type specific):EDIT: So, now that you’ve updated your question I think I understand it a bit better. There’s no reason you can’t collapse the different methods down to a single overload. If you can refactor the implementation so that the query is not retrieved from the object type, you may be able to improve and consolidate things further. A factory pattern may make things cleaner and more maintainable: