Skip to content
A simple library that facilitates runtime checks of code and allows to define preconditions and invariants within a method.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitattributes
.gitignore
LICENSE
README.md

README.md

Guard.NET

A simple library that facilitates runtime checks of code and allows to define preconditions and invariants within a method.

Its main purpose is to leverage the precondition checks that appear in almost all methods, through a clean interface that accentuates intention and eliminates confusion.

Usage

public void AddUser(User user)
{
    Guard.NotNull(user, nameof(user), "optional custom error message");  // throws ArgumentNullException
	
    // OR use an explicit Exception
    
    var invalidOperationException = new InvalidOperationException("custom message");
    Guard.NotNull(user, invalidOperationException); 
    
    ...

}
public void GetUserByName(string name)
{
    Guard.NotNullOrWhitespace(name, nameof(name), "optional custom error message"); // throws ArgumentException

    // OR use an explicit Exception
    
    var invalidOperationException = new InvalidOperationException("custom message");
    Guard.NotNullOrWhitespace(userName, invalidOperationException);
    
    ...
	
}
public void GetUsers(int pageSize)
{
    Guard.NotGreaterThan(pageSize, _maxPageSize, nameof(pageSize), "optional custom error message"); // throws ArgumentOutOfRangeException

    // OR use an explicit Exception
    
    var invalidOperationException = new InvalidOperationException("custom message");
    Guard.NotGreaterThan(pageSize, _maxPageSize, invalidOperationException);
    
    ...
	
}
public void UpdateEmailAddress(int userId, string newEmailAddress)
{
    Guard.For(() => userId < 0, new ArgumentException(nameof(userId)));
    Guard.For(() => Regex.IsMatch(newEmailAddress, _emailRegexPattern), new ArgumentException(nameof(newEmailAddress)));

    ...
	
}

Instalation

The Guard class can be used by installing Guard.NET nuget package available here.

Install-Package Guard.NET

The package has no external dependencies.

You can’t perform that action at this time.