Question

I'm in the early process of implementing a very simple "design by contract" static helper class, similar to NUnit's Assert. Ideally what I'm looking to do is pass in an expression, check if it's true, and if it isn't, throw a specific exception with any parameters or error messages. In an ideal world I would be doing something like this:

// ideal
Assert.True<ArgumentNullException>(user != null, "User", "User cannot be null");

// not so ideal
Assert.True(user != null, new ArgumentNullException("User", "User cannot be null");

Now, my problem is, the constraint on Assert.True<T> would be Exception, new(), in order for me to create a new exception of the desired type. The key problem I'm encountering is, firstly generic constructors do not allow parameters, and secondly, most properties on the Exception constructors are GET only.

Any help is greatly appreciated, thank you.

Was it helpful?

Solution 3

Thank you for your answers; I've found a slight work around in the form of System.Activator.CreateInstance, which was discussed in a very similar post found here: Casting Exceptions in C#:

throw (T) System.Activator.CreateInstance(typeof(T), message, innerException);

OTHER TIPS

I'm sure you're already aware of Microsoft's Code Contracts support, but in case you are not (and are therefore unknowingly reinventing the wheel) you can find out about them here:

http://research.microsoft.com/en-us/projects/contracts/

How about something like this:

Assert.True(user != null, () => new ArgumentNullException("User", "User cannot be null");

By delegating instantiation of the exception to an anonymous method, you are only constructing the exception when you need it. This also gets around your problem with instantiating the exception in your Assert class.

Assert.True could then look something like this:

public static True(bool condition, Action<Exception> exception)
{
    if(!condition) throw exception();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top