Skip to content

Latest commit

 

History

History
83 lines (56 loc) · 3.06 KB

README.md

File metadata and controls

83 lines (56 loc) · 3.06 KB

What is it? 🚀

aqua.tool.Validation provides C# source generated extension methods for argument validation.

This package is designed to work for various target frameworks and makes use of PolySharp to integrate with different C# language versions.

How to use

public void SampleMethod(string text)
{
  // Throw an ArgumentNullException if text is null.
  // Throw an ArgumentException if text is empty.
  text.AssertNotNullOrEmpty();
}

public void SampleMethod(IReadOnlyList<string> text)
{
  // Throw an ArgumentNullException if text is null.
  // Throw an ArgumentException if any element in text is null or empty.
  text.AssertItemsNotNullOrEmpty();
}

public void SampleMethod(MyType myValue)
{
  // Throw an ArgumentNullException if myValue is null.
  this.nonNullValue = myValue.CheckNotNull();
}

Assert vs. Check

Most validation methods exists in two flavors. While assert simply verifies the input (e.g. AssertNotNull), check also returns the input value to allow for fluent API style code (e.g. CheckNotNull).

Migrate validation code

Existing code can be migrated using regex find and replace in Visual Studio.

Replace throw new ArgumentNullException()

Replace someArgument ?? throw new ArgumentNullException(nameof(someArgument)) by someArgument.CheckNotNull():

  • Search regex pattern:

    (?<pre>[\s\.\(])(?<field>.+)\s\?\?\sthrow\snew\sArgumentNullException\(((nameof\(\k<field>\))|(\"\k<field>\"))\)
  • Replace regex pattern:

    ${pre}${field}.CheckNotNull()

Migrate validation code for version 2.2.0 and later

Starting with aqua.tool.Validation v2.2.0 the name argument can be omitted as it's atomatically injected by the compiler using the CallerArgumentExpressionAttribute.

Replace someArgument.CheckNotNull(nameof(someArgument)) by someArgument.CheckNotNull():

  • Search regex pattern:

    \.(?<method>((Assert)|(Check))(Items)?NotNull(OrEmpty)?)\(((nameof\([^\)]+\))|([^\)]+))\)
  • Replace regex pattern:

    .${method}()

    migrate validation code

Options

Code generation can be configured through some MSBuild properties to set in consuming projects.

Property Value Description
AquaToolValidationDisable true|false Disable compilation of generated source code.
AquaToolValidationPublic true|false Declare generated source code as public. By default, generated source code has internal visibility.
AquaToolValidationNullableDisable true|false Suppress nullable attributes.