I would like to be able to pass a class name as parameter to a method, and then inside that method create an object of that class with certain parameters.
A concrete (simplified) example:
This is a method to compute an OperationResult
private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides, IFailedOperationInfo failedOperationResult)
{
var exception = failedOperationResult.Exception.HasValue() ? failedOperationResult.Exception.Value() : null;
if (exception != null)
{
return new FailedResult<Unit>(
new InvalidBundleErrorKeyResolver(new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName, sides), exception)));
}
throw new InvalidOperationException("Failed operation result during bundle consistency check does not contain error or exception.");
}
Depending on the operation that we get the error from, we use different ErrorKeyResolvers. I would like to pass these ErrorKeyResolver as a parameter to the method, so that I don't need to make different GetFailedOperationResult methods for each error type.
Inspired by How to use class name as parameter in C# I tried something like this:
private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides,IFailedOperationInfo failedOperationResult, IErrorResourceKeyResolver resourceKeyResolver)
{
var exception = failedOperationResult.Exception.HasValue() ? failedOperationResult.Exception.Value() : null;
if (exception != null)
{
return new FailedResult<Unit>(Activator.CreateInstance(typeof(resourceKeyResolver),new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName, sides), exception)));
}
throw new InvalidOperationException("Failed operation result during bundle consistency check does not contain error or exception.");
}
But I cannot do typeof(resourceKeyResolver)
because I cannot use a variable as a type.
Is there a nice way to do this? Is it even a good thing to do? I also read that dynamics should be avoided so I wonder if saving some code repetition is worth it here.
EDIT: the input parameters should be: private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides,IFailedOperationInfo failedOperationResult, string resourceKeyResolver)
And from the class name as string I should be able to find the type.