Is there any functionality similar to Assert (Assertions) in C#?


In languages ​​like Python there is an assertion mechanism ( assert ) which aims to assert if an expression is true and, in case there are failures, it throws an exception.

In most cases, I think it's better to use a feature like assert rather than doing an if all the time and then throwing an exception.

Example (with assert):

 assert(value, 'Value is invalid')

Example (no assert )

 if not value:
     raise Exception('Value is invalid')

Since I'm studying C# right now, I'd like to know if there is any way, like the one demonstrated in the assert example, to throw an exception if an assertion fails.

Is there such functionality in C# or at least something close?


The System.Diagnostics.Debug class has several Assert methods you can use to do this.

In your case, for example:

Debug.Assert(value, "Value is invalid")

Calls to Debug.Assert are only compiled if you are compiling with the Debug option; if you compile on the Release option, the calls become a no-op, which makes them very interesting during development, but doesn't impact performance when you release your product.

Scroll to Top