In a helper class, use Activator.CreateInstance to instantiate the specific exception with its message so you don't litter your code with if statements to verify state.
Introduction
The typical assertion looks like this:
if (someConditionIsNotMet)
{
throw new SomeSpecificException("message");
}
However, I personally do not like littering my code with if
statements for assertions. What I prefer is:
Assertion.That(someConditionIsMet, "message");
but I lose the ability to specify the specific Exception
that I want thrown.
So what I want is something like:
Assertion.That<MyException>(someConditionIsMet, "message");
but the base class Exception
, while it has a parameterless constructor, won't let me assign the message after the exception is created. Note that Message
is a read only property in the Exception
class:
public virtual string Message { get; }
Activator.CreateInstance to the Rescue
My solution is to use Activator.CreateInstance
and pass in the specific exception type I want instantiated, along with the exception message.
public static class Assert
{
public static void That<T>(bool condition, string msg) where T : Exception, new()
{
if (!condition)
{
var ex = Activator.CreateInstance(typeof(T), new object[] { msg }) as T;
throw ex;
}
}
}
That's it - the where
verifies at compile time that the generic is of type Exception
and is an instance type.
If you know of a better way of doing this, let me know!
History
- 14th December, 2020: Initial version