Created
August 20, 2012 13:11
-
-
Save kcargile/3403869 to your computer and use it in GitHub Desktop.
.NET Object extension methods to shortcut null argument checks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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