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

Asked

Viewed 228 times

9

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

In most cases, I think it’s best to use a feature like assert than every time make a if and then throw an exception.

Example (with assert):

 assert(value, 'Value is invalid')

Example (without assert)

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

As I am studying C# now, I would like to know if there is any way, as demonstrated in the example of assert, to make an exception if a statement fails.

There is this functionality in C# or at least something approximate?

  • I think you misunderstood the assert from python, its two codes do not have the same functionality, are similar, but have the difference of assert only run in debug, if the program runs with optimizations assert will not run, so it serves only to help development https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

  • 1

    Dear @Leandrogodoyrosa and that is why the questioner asked the question, because if you do not understand the culture of the site, we often ask questions of which we already know the answer, but to generate good answers so that future visitors who have real doubt learn the right one, that’s what Wallace did, he knew the answer, asked the question and gave the opportunity for other people to answer it to serve as a source of learning.

2 answers

11

The class System.Diagnostics.Debug has several Assert methods that you can use for this.

In your case, for example:

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

The calls to Debug.Assert are only compiled if you are compiling with the Debug option; if you compile in the Release option, the calls become a no-op, which makes them very interesting during development, but without impacting performance when you launch your product.

  • That is to say, Debug.Assert() is not the same as throwing exceptions in the code when the expression fails. However, I believe your answer is correct compared to Python.

  • Depends. If the code is compiled with the Debug option, then if the Debug.Assert expression fails, it will play an exception - that is, it is equivalent (not necessarily equal) to throwing a code exception. But if the code is compiled in the Release option, then assert will not be executed (and no exception will be created, regardless of the parameters passed).

  • 2

    The point I’m trying to make, without any criticism to your answer (so much that I gave +1), is that Exceptions behave in a specific way, regardless of how code is compiled. Already the use of Debug.Assert() serves another purpose, that of showing code problems in debug mode, but being totally ignored in release compilation, different from what happens with exceptions.

  • 1

    True, although in practice on some occasions exceptions and asserts may have the same effect, they cannot (or at least should not) be exchanged for each other (unless you know exactly what you are doing).

9


There is the Assert() how do you know.

Depending on the framework of tests you use. You may have many others.

The . NET has contracts also. Can be useful in some scenarios where people use assert for lack of something better.

The assert is not a substitute for exceptions. Contracts can be better for this. As you can see in the documentation, the assert is for diagnosis, or even documentation. The exception mechanism is something that is part of the normal code and its execution is part of what is expected to be executed in certain abnormal circumstances, it is not just an extra that must disappear and only has function during development.

Even in many cases an assertion should be used when using the exception.

The assertion is only linked during the debug, and precisely why it is best suited to debug problematic code. When the application is built in mode release simply does not have the final binary (IL code) assertion code.

The mechanism serves to temporarily inform and hold the execution of the code when there are problems in something you expected to happen. It’s a way to establish a breakpoint conditional.

It would be interesting to see the documentation of the whole class Debug that has other very interesting features that help a lot the whole debugging process.

It is also useful to see the class Trace that can help understanding and debugging code. This class stays in mode release and is a way to get information on the actual functioning of the application. In general your methods should be very light to not impact the general execution and in most cases should run only for a while, until you have enough information of real use.

Although the specific resource is equal to Python, the Assert() of C# is part of a much more sophisticated mechanism that most ignore, mainly because it does not usually appear with the same frequency in codes in production, and as people tend to reproduce recipes, does not have a reference to copy.

Contracts

A resource that I find little explored is the contract. While C# could have done a better job, it’s great for laying down rules on how code should work and creating contracts for methods and types that can be checked at compile time and deciding whether it’s enough or should do something at runtime, probably casting an exception.

With this mechanism it is possible to improve performance while maintaining robustness. Remember that C#, unlike Pyhton, PHP, etc., performance is important, and robustness is of fundamental importance, so there is a preference for every check to occur at compile time. Contracts allow the execution time option to be made only when it is impossible to resolve at compile time. Codes with contracts have much less ifs and far fewer exceptions.

While the assertion serves to debug, contracts serve to ensure in code that everything is as expected. Even there is assertion within contracts, when it is important.

With the forgiveness of the same terms used in different contexts, code contracts are part of the contract of methods and types. When you use Require is making an extension of the parameter information.

I’m particularly fond of contracts (in general I don’t need to have runtime checks anymore, something is still very common in many codes out there). I don’t really understand why most people don’t use it. I’ve seen some criticism of it because it’s not perfect, but the option is so much worse. I understand that most programmers do not use because they do not know and because the bulk of the existing code, material and courses do not use, so it becomes a vicious cycle. But programmers who go beyond cake recipe also do not use as often as I think should.

Even contracts help tools automatically create much of the unit tests you need in your code. I don’t see people enjoying this. Interestingly I see many manual tests proving extremely flawed because programmers have difficulty understanding what they really need to test (of course manual tests are required in several cases). Either people don’t test anything or they do it without really understanding what they’re doing.

For me the Debug.Assert() just for something I know is temporary, which is rare, or even something exclusively internal. At least it was like that. Microsoft was removing the tools that existed and the contracts became less useful and the assertion gained a little weight. Let’s wait for a proposal to have contracts in the language.

  • More agile than an eagle +1

  • This! It is important to remember that assert does not exist in release mode. It exists only for debugging.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.