interface IExecutor
{
void Execute();
}
class Executor2<T> where T : IExecutor
{
public void Execute()
{
var ex = (T)Activator.CreateInstance(typeof(T));
ex.Execute();
}
}
It was a question at an interview. They told me that sometimes this code falls (causes exceptions) and there are at least 3 reasons that could cause the problems. It’s unknown what exceptions were there. But the method Execute was created good, its implementation has no fault.
Does anybody have a suggestion about that?
Edit: There are at least 3 reasons that could cause the problems. What are these reasons?
On the face of it I can see a few issues.
To explain 2: you specify a type
Tat the class definition with a constraint onIExecutor, but you then define another typeTat the method level without a constraint. This doesn’t compile.If I fix this and remove the
<T>definition from the method I can see a number of reasons for it failing without much warning:exis null.Tdoesn’t have a public parameterless constructor defined.T.As spotted by Jakub:
Tcould be an interface (no constructor).Tcould be an abstract class, these don’t allow instances to be created directly.The first can be guarded against using a null check
if (ex != null)and the second can be guarded against using another generic constraintnew():Obviously you could also amend your code to including exception logging. This might be useful in figuring out what the actual problems are instead of just stabbing in the dark:
This is the only answer I can cobble together considering I didn’t understand the question.
If I were asked this in an interview I’d likely say I couldn’t name all 3, but I’d know how to change the code to be more maintainable and tell me what was wrong. Then I’d likely walk for asking pointless interview questions.