Consider a factory method that I may or may not control, passed to another class as a Func<T>:
// this.FactoryMethod is an external dependency passed into this class
// through constructor or property injection assume that it is not null
// but there is no guarantee that it will return a non-null reference.
Func<IModel> FactoryMethod;
public IModel GetPopulatedModel(int state, FileInfo someFile)
{
// Argument validation omitted for brevity...
// This operation could return null.
var model = this.FactoryMethod()
if (model == null)
{
throw new SomeException("Factory method failed to produce a value.");
}
// Safe to assign to properties at this point.
model.Priority = state;
model.File = someFile;
return model;
}
I would like to throw something that indicates the operation failed.
ArgumentNullException would be misleading because there is nothing wrong with the arguments:
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
InvalidOperationException doesn't really seem to be on point:
The exception that is thrown when a method call is invalid for the object's current state.
It seems weird to consider a local variable to be part of the object's current state.
What would be good exception to throw? I'm surprised there is no OperationFailedException in System. Should I write my own exception, or is there a good one out there?
Func<T>to guarantee that, so I wouldn't be able to use the built in delegate and I'd have to build my own class or delegate type, which I'd like to avoid. - Jim Countsmodelwas not null. I suppose I could use astructto implement the pattern. But then I would have to program against that struct instead of theIModelinterface. - Jim Counts