Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created August 20, 2012 13:11
Show Gist options
  • Save kcargile/3403869 to your computer and use it in GitHub Desktop.
Save kcargile/3403869 to your computer and use it in GitHub Desktop.
.NET Object extension methods to shortcut null argument checks.
using System;
namespace Extensions
{
/// <summary>
/// Contains <see cref="object"/> extension methods.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Checks for and throws an <see cref="ArgumentNullException"/> if the object is null.
/// </summary>
/// <param name="param">The <see cref="object"/>.</param>
/// <exception cref="ArgumentNullException"><b>parm</b> was null.</exception>
public static void CheckNull(this object param)
{
param.CheckNull(null);
}
/// <summary>
/// Checks for and throws an <see cref="ArgumentNullException"/> if the object is null.
/// </summary>
/// <param name="param">The <see cref="object"/>.</param>
/// <param name="parmName">Name of the parameter to check.</param>
/// <exception cref="ArgumentNullException"><b>param</b> was null.</exception>
public static void CheckNull(this object param, string parmName)
{
if (param == null)
{
throw new ArgumentNullException(parmName);
}
}
}
}
using System;
using Extensions;
using NUnit.Framework;
namespace tests.Extensions
{
[TestFixture]
public class ObjectExtensionsFixture
{
[Test]
public void TestIsParameterNull()
{
new object().CheckNull();
object o = null;
Assert.Throws<ArgumentNullException>(() => o.CheckNull());
}
[Test]
public void TestIsParameterNullWithNull()
{
object obj = null;
Assert.That(() => obj.CheckNull(), Throws.TypeOf<ArgumentNullException>().With.Message.EqualTo("Value cannot be null."));
}
[Test]
public void TestIsParameterNullWithName()
{
new object().CheckNull("parameter1");
}
[Test]
public void TestIsParameterNullWithNullAndName()
{
object obj = null;
Assert.That(() => obj.CheckNull("parameter1"), Throws.TypeOf<ArgumentNullException>().With.Message.EqualTo("Value cannot be null.\r\nParameter name: parameter1"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment