Skip to content

Instantly share code, notes, and snippets.

@controlflow
Last active November 23, 2016 22:19
Show Gist options
  • Save controlflow/b3f8d55349c2ba2fa297652871c21e22 to your computer and use it in GitHub Desktop.
Save controlflow/b3f8d55349c2ba2fa297652871c21e22 to your computer and use it in GitHub Desktop.
// good old if-then-throw
if (foo == null)
throw new ArgumentNullException("foo");
// nameof-flavored if-then-throw
if (foo == null)
throw new ArgumentNullException(nameof(foo));
// reference equality to avoid operator== overload
if (ReferenceEquals(foo, null))
throw new ArgumentNullException(nameof(foo));
// one more way to avoid operator== overload
if ((object) foo == null)
throw new ArgumentNullException(nameof(foo));
// and one more way
if (!(foo is object))
throw new ArgumentNullException(nameof(foo));
// code contracts
Contract.Requires(foo != null);
// debug assert
Debug.Assert(foo != null);
Trace.Assert(foo != null)
// user-defined util
Require.NotNull(foo);
Check.NotNull(foo, nameof(foo));
// C# 7.0 throw-expression powered way
foo = foo ?? throw new ArgumentNullException(nameof(foo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment