Skip to content
An experiment in guarding against null arguments
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.
.nuget
NullGuard.PostSharp
Tests
.gitattributes
.gitignore
Build-Solution.ps1
LICENSE
NullGuard.6.1.ReSharper Initial implementation of NullGuard.PostSharp Jan 5, 2013
NullGuard.msbuild
NullGuard.sln
NullGuard.sln.DotSettings
README.md
build.bat

README.md

NullGuard

The null reference has been called "my billion dollar mistake" by its inventor, Tony Hoare. Guarding against null arguments and return values ends up resulting in a lot of boilerplate code.

This library attempts to remove the repetitive work of all that argument null checking by rewriting IL to check all nullable arguments. For more details, check out the blog post announcing this library.

Install this library.

Install-Package NullGuard.PostSharp

You can apply the EnsureNonNullAspect attribute to individual classes, methods, or an entire assembly. You'll also need to install the PostSharp Visual Studio Extension. This library should work fine with the free community edition.

Usage Examples

using NullGuard;

[assembly: EnsureNonNullAspect]

public class Sample 
{
    public void SomeMethod(string arg) {
        // throws ArgumentNullException if arg is null.
    }

    public void AnotherMethod([AllowNull]string arg) {
        // arg may be null here
    }

    public string MethodWithReturn() {
        // Throws InvalidOperationException if return value is null.
    }
   
    // Null checking works for automatic properties too.
    public string SomeProperty { get; set; }

    [AllowNull] // can be applied to a whole property
    public string NullProperty { get; set; }

    public string NullProperty { 
        get; 
        [param: AllowNull] // Or just the setter.
        set; 
}

Note

For this specific aspect, the code generated by PostSharp Professional Edition 2.1 will be much cleaner and faster than the one generated by PostSharp Starter Edition 2.1 because of the optimizer included in the paid edition. The implementation with PostSharp 3 will be even more better.

You can’t perform that action at this time.