The page has been moved to GitHub

CodeContractExtensions

Package: MyToolkit
Platforms: PCL

The class provides extension methods for validating method parameters. The methods throw an ArgumentNullException and provide Code Contracts for the calling methods.

The following code shows their usage:

public void Foo(object a, string b)
{
    a.CheckNotNull("a");
    b.CheckNotNullOrEmpty("b");

    ...
}

This is the same as writing:

public void Foo(object a, string b)
{
    Contract.Requires(a != null);
    Contract.Requires(b != null);
    Contract.Requires(b != string.Empty);
    
    if (a != null)
        throw new ArgumentNullException("a");
    if (string.IsNullOrEmpty(b))
        throw new ArgumentNullException("b");

    ...
}

For better refactoring support, use the nameof operator (C# 6 only):

public void Foo(object a, string b)
{
    a.CheckNotNull(nameof(a));
    b.CheckNotNullOrEmpty(nameof(b));

    ...
}

Note: The extension methods in the MyToolkit.Legacy PCL library do not support Code Contracts, but they throw ArgumentNullExceptions.

Source code

The CodeContractExtensions class has no dependencies to the MyToolkit library and can also be used as "standalone" class:

Last edited Jun 3, 2015 at 10:02 PM by rsuter, version 13