C#: Code Contracts vs. normal parameter validation
In order to get rid of warnings you can use Contract.Assume
In order to get rid of warnings you can use Contract.Assume
The Contract Reference Assembly is a special kind of assembly which preserves any code contracts you defined in your source code files. This is necessary because at compile-time, the code contracts’ “rewriter” (ccrewriter) removes or replaces each contract with equivalent verification code (Contract.Requires(someBool) might be rewritten as if (!someBool) throw). Without the code contracts, if … Read more
As mentioned by other comments in this question, you should remove the generic type identifier from your attribute usage as it can not be resolved at compile time: [ContractClass(typeof(IRandomWriteAccessibleContract<>))]
Imagine you have a method like this: bool ContainsAnX(string s) { return s.Contains(“X”); } Now, this method will always fail if you pass null to it, so you want to ensure this never happens. This is what Contract.Requires is for. It sets a precondition for the method, which must be true in order for the … Read more
I’ve had an answer on the MSDN forum. It turns out I was very nearly there. Basically the static checker works better if you split out “and-ed” contracts. So, if we change the code to this: public static int RollDice(Random rng) { Contract.Ensures(Contract.Result<int>() >= 2); Contract.Ensures(Contract.Result<int>() <= 12); if (rng == null) { rng = … Read more
From The Code Contracts User Manual: Contracts allow you to express preconditions, postconditions and object invariants in your code for runtime checking, static analysis, and documentation. Code Contracts are used for static verification; imagine if – at compile time – you caught not only syntax errors but also logic errors. This is the vision of … Read more
I know this doesn’t directly answer your question, but it appears you’re using a legacy mode for Code Contracts. This document describes the recommended assembly mode based on usage requirements: http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf From Pages 20, 21… Another snippet from the document: 5.1.1 Assembly Mode The contract tools need to know which usage mode you choose. If … Read more
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 … Read more
Just ran into this same problem. I finally found out that I catched different exceptions with the same name, like you did: catch (ReflectionTypeLoadException ex) { // … } catch (Exception ex) { // ex is not null! // … } Both are named ‘ex’. Changing one of both names solved this problem for me, … Read more