I wonder, how to properly use Code Contracts in .NET Core, so far I tried to add CC to my project, compile and debug. I'm confused by message, which is appearing in each call which uses Contract.Requires
, and information found by googling.
The message states:
An assembly must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling
Contract.Requires<TException>
andCONTRACTS_FULL
symbol is defined. Remove any explicit definitions of theCONTRACTS_FULL
symbol from your project and rebuild. CCRewrite ....
As I can see there are no CC options in the project properties and as I can see CC's Github repository is nearly dead. Is the are any way how to successfully use CC in .NET Core?
And if not, is there any simple way how to replace them? I use Contract.Requires
and ContractClassAttribute
. Replacing Contract.Requires
is obvious, but ContractClassAttribute is blowing my mind :-)
The answer is: Code Contracts is no longer supported for .NET Core. It's available in the .NET Core 2.0, but it's no longer maintained.
See the official statement at the docs page:
Note
Code contracts aren't supported in .NET 5+ (including .NET Core versions). Consider using Nullable reference types instead.
Also on Github thread (Are Code Contracts going to be supported in .NET Core going forwards? #6361):
We have stopped investing in code contracts a while ago. We've added it to .NET Core 2.0 as part of our compatibility effort, but I wouldn't recommend new code using it.
FWIW, we've looked at many code bases that use them and it seems the overwhelming usage is about null handling. The replacement for this is under way with C# 8's nullable-reference types.
— Immo Landwerth, Program manager on the .NET team at Microsoft. https://twitter.com/terrajobst