Lightweight guard / pre-condition / parameter validation library for .NET
PM> Install-Package 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
}
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)
{
throw new ArgumentException(
message: $"{guard.Name} should satisfy custom condition.",
paramName: guard.Name);
}
}
return guard;
}
Now you can use your custom guard:
void ExampleMethod(CustomType value)
{
Guard.Requires(value).SatisfiesCustomCondition();
// method body
}
Copyright Matthew King 2012-2022.
NGuard is licensed under the MIT License. Refer to license.txt for more information.