Can I use or "cast" the type of a class, for instance type of the class CustomClass
, therefor typeof(CustomClass)
, to execute a method which relies on providing its corresponding class CustomClass
as an "argument"?
Method<CustomClass>();
How could I achieve this by only knowing typeof(CustomClass)
?
Detailed question:
I'm developing a Web API in ASP.NET 4.5. I have access to an extension method, that I cannot change, for the Startup's IAppBuilder app:
public static class AppExtensions
{
public static void AddExceptionTranslation<TException>(
this IAppBuilder app,
HttpStatusCode statusCode,
Func<TException, ApiErrors> messageGenerator))
where TException : Exception;
}
This extension method is used to convert custom exceptions, which extend Exception
, to its appropriate status codes. I'm using it as follows:
public static void SetUpExceptionHandling(IAppBuilder app)
{
app.AddExceptionTranslation<CustomException>(HttpStatusCode.BadRequest, e => e.ToApiErrors());
app.AddExceptionTranslation<CustomUnauthException>(HttpStatusCode.Forbidden, e => e.ToApiErrors());
// ...
}
Right now I have to manually add an entry for every single custom exception, providing the TException
in each case. I'm already maintaining a data structure which contains the typeof
for each custom exception class, alongside with its appropriate status codes, unique ids and other properties that I only want to maintain in one place.
I'd like to use this existing data structure to iterate through it and execute AddExceptionTranslation<TException>
for each custom exception, where I know their Type
.
Is this possible? If not, would it be possible if my data structured contained something else? Sure, I could just bite the bitter apple and add each new custom exception to the data structure and manually add an entry for the method execution but I'd really like to automate the latter.
Please let me know if I can clarify. Thanks!
Edit
AddExceptionTranslation actually accepts a second argument, a lambda expression, that's applied to the custom exception:
app.AddExceptionTranslation<CustomException>(HttpStatusCode.Forbidden, e => e.ToApiErrors());
I didn't think it would be relevant to the question but since it's interfering with the suggested solution/duplicate I'm in quite the pickle. Can I still invoke the method in some way?