Recently I came across the problem of creating an exception with a given message from within a generic method. For instance, the following code works as expected:
public static void Throw<T>() where T : Exception, new()
{
throw new T();
}
...
public static void Main()
{
Throw<ArgumentOutOfRangeException>(); // Throws desired exception but with a generic message.
}
However, I would like to be able to write
public static void Throw<T>(string message) where T : Exception, new()
{
T newException = new T();
newException.Message = message; // Not allowed. 'Message' is read-only.
throw newException;
}
...
public static void Main()
{
Throw<ArgumentOutOfRangeException>("You must specify a non-negative integer."); // Throws desired exception.
}
Is there any way of achieving this without the use of reflection either to change the value of the Message
property or dinamically activate an instance of the type with the desired parameters?