For example, you usually don\'t want parameters in a constructor to be null, so it\'s very normal to see some thing like
if (someArg == null)
{
throw new Arg
public static class Ensure
{
///
/// Ensures that the specified argument is not null.
///
/// Name of the argument.
/// The argument.
[DebuggerStepThrough]
[ContractAnnotation("halt <= argument:null")]
public static void ArgumentNotNull(object argument, [InvokerParameterName] string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
}
}
usage:
// C# < 6
public Constructor([NotNull] object foo)
{
Ensure.ArgumentNotNull(foo, "foo");
...
}
// C# >= 6
public Constructor([NotNull] object bar)
{
Ensure.ArgumentNotNull(bar, nameof(bar));
...
}
The DebuggerStepThroughAttribute
comes in quite handy so that in case of an excpetion while debugging (or when I attach the debugger after the exception occurred) I will not end up inside the ArgumentNotNull
method but instead at the calling method where the null reference actually
happend.
I am using ReSharper Contract Annotations.
ContractAnnotationAttribute
makes sure that I never misspell
the argument ("foo"
) and also renames it automatically if I rename
the foo
symbol. NotNullAttribute
helps ReSharper with code analysis. So if I do new Constructor(null)
if will get a warning from ReSharper that this will lead to an exception.