If you mean that you may have a generic type or method parameter, you could do this:
public class A<T> where T : ITask, new()
{
public void Some()
{
T instanceOfITask = new T();
}
}
...or:
public class A
{
public void Some<T>() where T : ITask, new()
{
T instanceOfITask = new T();
}
}
Generic constraints let you specify that T
must implement ITask
and must have a public parameterless constructor.
UPDATE
As OP has edited the question maybe my current answer got obsolete.
By the way, as I don't know your actual requirements, I could argue that you can still go with this solution.
Instead of doing the if some condition inside the method that should handle instances of ITask, you could do in the caller and take advantage of generic constraints again to avoid reflection and its performance penalties.
At the end of the day, this is using the abstract factory pattern:
// The abstract factory!
public static class TaskFactory
{
public static T Create<T>() where T : ITask, new()
{
T instanceOfITask = new T();
// more stuff like initializing default values for the newly-created specific task
return instanceOfITask;
}
}
Later, somewhere:
ITask task = null;
// Depending on the condition, you invoke the factory method with different implementation of ITask
if([some condition])
{
task = TaskFactory.Create<MySpecificTaskImplementationA>();
}
else
{
task = TaskFactory.Create<MySpecificTaskImplementationB>();
}