How to properly use Code Contracts in .NET Core

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

Leave a Comment