Skip to content

An experiment in guarding against null arguments

License

Notifications You must be signed in to change notification settings

gfraiteur/NullGuard

 
 

Repository files navigation

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.

About

An experiment in guarding against null arguments

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 97.2%
  • PowerShell 2.8%