As far as I read in a nutshell book, code contracts could degrade the runtime performance.
Is it possible to disable code contracts in production?
As far as I read in a nutshell book, code contracts could degrade the runtime performance.
Is it possible to disable code contracts in production?
The user manual explains this in a fair amount of detail - there are all kinds of options you can have. Each build configuration can have different settings for which contracts are checked at execution time, and it's not an "all or nothing" choice - you can enforce all, some or none of the contracts, based on settings which can be tweaked in Visual Studio.
I have my favorite options described on my blog.
To summarize:
Some people prefer Preconditions to be included in their Release build. This is particularly useful if distributing via NuGet because they don't support Code Contract dlls. For my NuGet packages, I'm migrating towards including Preconditions in the Release builds, but also having a separate download for a "Release without Preconditions" build.
The performance difference is quite small and will not affect your code in a noticeable way. Unless you are developing some real-time stock trading system, I seriously wouldn't even worry about it.
As far as disabling the code in Production, I would far rather have the added protection of Code Contracts instead of some possibly obscure error. An error in the code contract will tell you exactly where and why the Contract was violated as opposed to having to dig down in some deep call-stack just because some bad data was passed in 5 levels up the call-stack tree.
@svanryckeghem and @Stephen Cleary:
If you are using or are planning to use Contract.Requires<TException>
and do not enable 'Runtime Contract Checking', you'll get a runtime failure about the IL rewriter (ccrewrite.exe) needing to be bound to the usage of Code Contracts. You will then be required to enable Runtime Contract Checking to get this to work.
IMHO, the use of Contract.Requires<TException>()
is far more useful than Contract.Requires()
since you have control over the type of exception thrown.
In your project properties, go to Code Contract, select the "Release" Configuration and uncheck runtime checking.
© 2022 - 2024 — McMap. All rights reserved.
Contract.Requires<TException>()
, I disagree that this is more useful, I think it's more of a legacy thing- I don't use it at all. The contract requires are almost all argument exceptions of one sort or another and the boolean condition is sufficient information; if you design things appropriately.Contracts
aren't just another way of doingException
s, they require a different approach. – Serb