-
Notifications
You must be signed in to change notification settings - Fork 75
CodeContractExtensions
Rico Suter edited this page Jun 10, 2015
·
3 revisions
- 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.
The CodeContractExtensions class has no dependencies to the MyToolkit library and can also be used as "standalone" class: