Click here to Skip to main content
15,746,202 members
Articles / Programming Languages / C#
Posted 14 Dec 2020

Tagged as


9 bookmarked

Assert with Assertion!

Rate me:
Please Sign up or sign in to vote.
4.88/5 (9 votes)
14 Dec 2020CPOL
Instantiate the exception that you want in an assertion
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.


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!


  • 14th December, 2020: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Architect Interacx
United States United States
Home Page:

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

QuestionAn Alternative Suggestion Pin
George Swan16-Dec-20 7:17
mveGeorge Swan16-Dec-20 7:17 

As another alternative, you could use something like this.

public static void Other<T>(bool condition, string msg) where T : Exception, new()
     if (!condition)
         var constructorInfo = typeof(T).GetConstructor(new Type[] { typeof(string) });
         var ex= constructorInfo.Invoke(new object[] { msg, });
         throw (T)ex;

There is very little difference between the two methods.

|      Method |     Mean |     Error |    StdDev | Ratio | RatioSD | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------ |---------:|----------:|----------:|--:|--------:|-:|-------:|--:|--:|----------:|
| AssertOther | 8.285 us | 0.1197 us | 0.0934 us |  0.93 |    0.03 |    1 | 0.1221 |     - |     - |     520 B |
|  AssertThat | 8.813 us | 0.1608 us | 0.2550 us |  1.00 |    0.00 |    2 | 0.1984 |     - |     - |     848 B |

QuestionMore Alternatives Pin
Ian Good15-Dec-20 23:55
Ian Good15-Dec-20 23:55 
AnswerRe: More Alternatives Pin
Marc Clifton16-Dec-20 3:08
mvaMarc Clifton16-Dec-20 3:08 
GeneralRe: More Alternatives Pin
wvd_vegt16-Dec-20 9:16
professionalwvd_vegt16-Dec-20 9:16 
GeneralRe: More Alternatives Pin
Ian Good16-Dec-20 19:42
Ian Good16-Dec-20 19:42 
QuestionBetter Way to Do This Pin
AndyHo15-Dec-20 4:53
professionalAndyHo15-Dec-20 4:53 
AnswerRe: Better Way to Do This Pin
Marc Clifton15-Dec-20 10:30
mvaMarc Clifton15-Dec-20 10:30 
GeneralRe: Better Way to Do This Pin
AndyHo15-Dec-20 13:04
professionalAndyHo15-Dec-20 13:04 
GeneralMy vote of 5 Pin
Daniele Alberto Galliano15-Dec-20 3:47
professionalDaniele Alberto Galliano15-Dec-20 3:47 
QuestionIdea ok Pin
wvd_vegt14-Dec-20 23:23
professionalwvd_vegt14-Dec-20 23:23 
AnswerRe: Idea ok Pin
Marc Clifton15-Dec-20 2:08
mvaMarc Clifton15-Dec-20 2:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.