Let’s say I have a factory ressembling this:
public static class BusinessObjectFactory
{
public static T Create<T>(int objectId) where T : BusinessObject, new()
{
var dataSource = DataLayer.DataSources.Repository.Get<T>();
var serializer = DataLayer.Serializers.Repository.Get<T>();
var businessObject = new T {ObjectId = objectId, DataSource = dataSource, Serializer = serializer};
return businessObject;
}
}
This works provided I have public accessors for ObjectId, DataSource and Serializer.
I would rather specify these arguments in my type T constructor, knowing that
T is constrained as a BusinessObject and a BusinessObject has that kind of
constructor.
I know that I could replace my call to new T with something like this:
var businessObject = (T) Activator.CreateInstance(typeof (T), objectId, dataSource, serializer);
But what is the technical reason why my T constructor must be parameterless? I feel there is something I don’t understand about generics. I’ve seen several questions floating around on SO related to that topic but no answer that really enlightened me.
Generics are compile-time artifacts. That means that at compile-time there will be new generated suitable class.
At compile time the parameter of the ctor, could not be yet identified (if it’s not a constant).
That’s why you have to have an “empty” ctor, that CLR is able to contsuct your type’s object.