Fast, extensible, intuitive and easy-to-use C# portable library providing fluent APIs for argument validation. Gives everything you need to implement defensive programming (http://veskokolev.com/2014/04/27/defensive-programming-technique-the-way-to-fast-failure/) in your .NET applications.
The supported frameworks are: - .NET Framework 4 and higher; - Silverlight 4 and higher; - Windows Phone 7 and higher; - .NET for Windows Store apps; - Xbox 360.
The library is available in the NuGet Gallery here. Just type: PM> Install-Package Bytes2you.Validation
Guard.WhenArgument(argument, "argument").Rule1().Rule2()...RuleN().Throw();
Based on the argument type there are different things that we can validate that make sense for that type (such as IsEmpty validation for string/guid/collection, etc.) and the library throws the right excpetion (ArgumentException, ArgumentNullException, ArgumentOutOfRangeException) following the best practicies.
Examples: Instead of...
public void SomeMethod(string stringArgument)
{
if (stringArgument == null)
{
throw new ArgumentNullException("stringArgument");
}
if (stringArgument == "xxx")
{
throw new ArgumentException("Argument is equal to <xxx>.", "stringArgument");
}
}
...we can use
public void SomeMethod(string stringArgument)
{
Guard.WhenArgument(stringArgument, "stringArgument").IsNullOrEmpty().IsEqual("xxx").Throw();
// Which means - when stringArgument is null or empty OR is equal to "xxx" we will throw exception. If it is null, we will throw ArgumentNullException. If it is equal to "xxx", we will throw ArgumentException.
}
Guard.WhenArgument<T>(argument, "argument")
For all T:
.IsEqual(value);
.IsNotEqual(value);
When T is class:
.IsNull();
.IsNotNull();
.IsInstanceOfType(type);
.IsNotInstanceOfType(type);
When T is Nullable:
.IsNull();
.IsNotNull();
When T is bool:
.IsTrue();
.IsFalse();
When T is IComparable:
.IsLessThan(bound);
.IsGreaterThan(bound);
.IsLessThanOrEqual(bound);
.IsGreaterThanOrEqual(bound);
When T is IEnumerable:
.IsNullOrEmpty();
.IsNotNullOrEmpty();
When T is Guid:
.IsEmptyGuid();
.IsNotEmptyGuid();
When T is string:
.IsEmpty();
.IsNotEmpty();
.IsNullOrEmpty();
.IsNotNullOrEmpty();
.IsNullOrWhiteSpace();
.IsNotNullOrWhiteSpace();
.IsEqual(value, comparisonType);
.IsNotEqual(value, comparisonType);
When T is float/double:
.IsNaN();
.IsNotNaN();
.IsInfinity();
.IsNotInfinity();
.IsPositiveInfinity();
.IsNotPositiveInfinity();
.IsNegativeInfinity();
.IsNotNegativeInfinity();
When T is byte/short:
.IsEqual(value);
.IsNotEqual(value);
.IsLessThan(bound);
.IsGreaterThan(bound);
.IsLessThanOrEqual(bound);
.IsGreaterThanOrEqual(bound);
The codebase is fully covered with unit tests (100% code coverage). Performance tests are also presented ensuring that the library will not affect the performance of your applications.
One can easily add new rules (see ValidationRules namespace) and expose them thought fluent API extensions (see FluentExtensions namespace).