How does dot net core process Arg.NotNull and Contract.Requires assets

567 Views Asked by At

In the aspnet-api-versioning I have found out a codeblock:

DefaultApiControllerFilter( IEnumerable<IApiControllerSpecification> pecifications )
        {
            Arg.NotNull( specifications, nameof( specifications ) );
            this.specifications = specifications.ToArray();
        }

The interested block is Arg.NotNull( value, "text" ); from the Microsoft namespace.

And there are several similar asserts in the code. Another example is Contract.Requires() from System.Diagnostics.Contracts

Tried to search over Microsoft docs about work principles but didn't found info.

So maybe could help to find out how does it work: like postsharp code rewrite, provide runtime conditional check as Debug.Assert or maybe simply throws exceptions(but it doesn't mention in docs)?

2

There are 2 best solutions below

2
Ananke On

They are code contracts (see https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts and https://www.microsoft.com/en-us/research/project/code-contracts/?from=http%3A%2F%2Fresearch.microsoft.com%2Fen-us%2Fprojects%2Fcontracts%2Fuserdoc.pdf)

Unfortunately they didn't really take off and the project was kind of abandoned, which is a shame as they had potential.

1
Stadub Dima On

After downloading library sources, compile and get look through compiled code found out that Microsoft::Arg is just a shared code project with a method

internal static void NotNull<T>(T value, string name) where T : class 
    {
      if ((object) value == null)    throw new ArgumentNullException(name);
    }

and the Contract.Requires(condition) is an Code Contract Assert codegenration extension which ...doesn't produce any code becuse of absence of the assert post build event. The similar sutuation on stackowerflow .