Reputation:
I've been fooling around with generic methods lately and came across methods that look like this:
public static void Requires<TException>(bool condition, string message) where TException : Exception
To my understanding, when using the above method you provide a Type
that inherits from Exception
and if the condition
is false
the provided Exception
type is thrown.
How does this work under the hood?
Is the TException
instantiated like so throw new TException();
?
And how can you pass in the message
parameter if the Type
is unknown to the method (all it knows is that it inherits type Exception
)?
Upvotes: 0
Views: 181
Reputation: 2410
According to MSDN : System.Exception does have constructor that takes a string as argument. This string represents the message.
With the help of the Activator-Class you can do the following pretty simple:
using System;
public class Test
{
public static void Requires<TException>(bool condition, string message)
where TException : Exception
{
Exception exception = (Exception)Activator.CreateInstance(typeof(TException),message);
throw exception;
}
public static void Main()
{
try
{
Requires<ArgumentNullException>(true,"Test");
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
Working example: http://ideone.com/BeHYUO
Upvotes: 3
Reputation: 6463
And how can you pass in the message parameter if the Type is unknown to the method
Similarly to Ned Stoyanov's answer, it's up to the person implementing the method to decide how this parameter will be used. It can be used as a message imbedded in the exception, it can be used somewhere else or it can be not used at all. The parameter name only suggests what it will be used for, but the caller has no guarantee that it will be used as he expects. It could be called djfhsfjfh
as well .
Upvotes: 1
Reputation: 13495
To my understanding, when using the above method you provide a Type that inherits from Exception and if the condition is false the provided Exception type is thrown.
That depends on the implementation of the method, all it is saying is that the type parameter of the Requires
method must have a base type of Exception
. But it is highly likely that it creates an exception of that type if the condition is false
. One way to do that is with Activator.CreateInstance
method.
Upvotes: 2