Lightweight guard / pre-condition / parameter validation library for .NET
C#
Latest commit 255c951 Jul 3, 2016 @MatthewKing Bump version number.
Permalink
Failed to load latest commit information.
src/NGuard
.gitattributes Added .gitattributes and .gitignore. Sep 17, 2012
.gitignore Convert to project.json format and add support for .NET Core. May 31, 2016
NGuard.sln Convert to project.json format and add support for .NET Core. May 31, 2016
global.json Add support for .NET Core RTM bits. Jul 3, 2016
license.txt
readme.md Clean up readme. Jun 2, 2016

readme.md

NGuard

Introduction

Lightweight guard / pre-condition / parameter validation library for .NET

Installation

PM> Install-Package NGuard

Using NGuard

You can use a guard to ensure your method parameters match certain preconditions:

void ExampleMethod(string input)
{
    Guard.Requires(input, nameof(input)).IsNotNull();

    // method body
}

Multiple guards can be chained together:

void ExampleMethod(string input)
{
    Guard.Requires(input, nameof(input)).IsNotNull().IsNotEmpty().IsNotWhiteSpace();

    // method body
}

Defining a custom guard

Custom guards are easy to write. Just create a new extension method:

static Guard<CustomType> SatisfiesCustomCondition(this Guard<CustomType> guard)
{
    if (guard.Value != null)
    {
        bool valid = /* code to test custom condition */
        if (!valid)
        {
            string paramName = guard.ParameterName;
            string message = $"{paramName} should satisfy custom condition.";
            throw new ArgumentException(message, paramName);
        }
    }

    return guard;
}

Now you can use your custom guard:

void ExampleMethod(CustomType value)
{
    Guard.Requires(value, nameof(value)).SatisfiesCustomCondition();

    // method body
}

Copyright

Copyright Matthew King 2012-2016.

License

NGuard is licensed under the MIT License. Refer to license.txt for more information.