0

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)?

Stadub Dima
  • 858
  • 10
  • 24

2 Answers2

1

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.

Ananke
  • 1,250
  • 9
  • 11
  • after sources download found out that there are 2 different namespaces - Microsoft and System.Diagnostics.Contracts - so updated question text – Stadub Dima Feb 18 '19 at 11:55
  • @DimaS the key word is `abandoned`. Even if you compile the source for .NET Core, there are no tools to validate the contracts – Panagiotis Kanavos Feb 18 '19 at 12:07
0

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 .

Stadub Dima
  • 858
  • 10
  • 24
  • 1
    And that's become obsolete now that .NET Core 3.0 and C# 8 added nullable references. This snippet isn't an example of code contracts either, it's just a guard clause. Nullable references or Roslyn analyzers are far more powerful than that. – Panagiotis Kanavos Feb 18 '19 at 12:08