A simple library providing argument validation methods and Code Contracts helpers.
NuGet package available here.
A precondition is a condition that must be true at the beginning of the execution of a method; argument validation is one such condition, and certainly the most common.
We provide four static classes to write preconditions:
Require
uses Code Contracts preconditions and throws an exception on failure.Enforce
only throws an exception on failure. It complementsRequire
when the condition is too complex for the Code Contracts tools.Expect
only uses Code Contracts preconditions.Demand
uses Code Contracts preconditions and debug assertions (Debug.Assert
).
Only Require
and Enforce
method calls survive in retail builds, that is
when selecting the Release configuration and when not defining
the CONTRACTS_FULL
symbol.
If you verify your code with the Code Contracts tool,
- for public methods, use
Require
orEnforce
when a condition is compulsory, useExpect
otherwise - for internal/private methods, use
Demand
when a condition is compulsory - be very careful with protected methods, if your class is not sealed you can't know in advance if the caller will satisfy the condition.
In any case, never use Demand
to guard a public method.
Requirements:
- Visual Studio 2015
- Code Contracts extensions
Before publishing the NuGet package, do not forget to update the version number in nuspec and AssemblyInfo. Build the project, then
nuget.exe pack Narvalo.Cerbere.nuspec
nuget.exe push -Source https://www.nuget.org/ Narvalo.Cerbere.X.Y.Z.nupkg
Adapted from a MSDN blog.
Unfortunately, CCCheck will still complain with CodeContracts: requires unreachable. You can safely suppress this warning and, later on, if you reach the "unreachable" point, CCCheck will produce a different warning: This requires, always leading to an error, may be reachable. Are you missing an enum case?.
Adapted from a blog post.