Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning.
I want to have a method where I can sa
You can almost do it like this:
static void TestException(string message) where E : Exception, new()
{
var e = new E();
e.Message = message;
throw e;
}
However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor.
I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this:
static void TestException(string message) where E : Exception
{
throw Activator.CreateInstance(typeof(E), message) as E;
}
Edit Oops just realised you're wanting to return the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.