C # code contracts and null checking

In my code, I do this a lot:

myfunction (parameter p) { if(p == null) return; } 

How can I replace this with a code contract?

I am interested to know if the pool passed and caught a static check.

I am interested in excluding a contract exception if null was sent during our testing

For production, I want to exit the function.

Can code contracts do this at all? Is this a good option for code contracts?

+4
source share
3 answers

The syntax for this is:

 Contract.Requires(p != null); 

This should be at the top of the method. All Contract.Requires (and other contract statements) must precede all other statements in the method.

+3
source

These posts here and here have many great options.

Edit: I am reading your post incorrectly for the first time, thinking that you are throwing an ArgumentNullException or something else until I see a Jon Skeet comment. I would definitely suggest using at least one of the many approaches presented in related issues.

Playback of one of John Faminella's answers here:

 [Pure] public static double GetDistance(Point p1, Point p2) { CodeContract.RequiresAlways(p1 != null); CodeContract.RequiresAlways(p2 != null); // ... } 
+1
source

Stumbled upon this question while researching code contracts for our code base. The answer here is incomplete. Publish this for future reference.

How can I replace this with a code contract?

The code is pretty simple. Replace the zero execution check on this line. This will throw an exception of type System.Diagnostics.Contracts.ContractException (which you apparently cannot catch explicitly, unless you catch all the exceptions, it is not intended to be detected at runtime).

 Contract.Requires(p != null); 

I am interested to know if the pool passed and caught a static check.

You can use the Microsoft plugin for static analysis of Code Contract, found here .

I am interested in excluding a contract exception if null was sent during our testing

Use the following, above:

 Contract.Requires(p != null); 

Alternatively, if you want to throw another exception (e.g. ArgumentNullException ), you can do the following:

 Contract.Requires<ArgumentNullException>(p != null, "Hey developer, p is null! That a bug!"); 

However, this requires a binary rewriting of Code Contracts code, which is included in the Code Contract plugin.

For production, I want to exit the function.

From what I understand, creating your project in Release mode will disable the verification of the contract code (although you can override this in your project properties). So yes, you can do it.

Can code contracts do this at all? Is this a good option for code contracts?

The short answer is yes.

+1
source

Source: https://habr.com/ru/post/1335603/


All Articles