From c48cb5227921d9bb9a70c21c4344cd1b4ab2e90d Mon Sep 17 00:00:00 2001 From: Bradley Grainger Date: Sun, 7 Feb 2010 01:27:12 -0800 Subject: [PATCH] Added EmptyIfNull. Closes #9. From http://code.logos.com/blog/2008/03/emptyifnull.html --- src/Logos.Utility/EnumerableUtility.cs | 11 +++++++++++ tests/Logos.Utility.Tests/EnumerableUtilityTests.cs | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Logos.Utility/EnumerableUtility.cs b/src/Logos.Utility/EnumerableUtility.cs index 543503d..6a2bc36 100644 --- a/src/Logos.Utility/EnumerableUtility.cs +++ b/src/Logos.Utility/EnumerableUtility.cs @@ -10,6 +10,17 @@ namespace Logos.Utility /// public static class EnumerableUtility { + /// + /// Returns the source sequence, or an empty sequence if is null. + /// + /// The source sequence. + /// The source sequence, or an empty sequence if is null. + /// See EmptyIfNull. + public static IEnumerable EmptyIfNull(this IEnumerable source) + { + return source ?? Enumerable.Empty(); + } + /// /// Computes the sum of a sequence of values. /// diff --git a/tests/Logos.Utility.Tests/EnumerableUtilityTests.cs b/tests/Logos.Utility.Tests/EnumerableUtilityTests.cs index 4e523da..468021f 100644 --- a/tests/Logos.Utility.Tests/EnumerableUtilityTests.cs +++ b/tests/Logos.Utility.Tests/EnumerableUtilityTests.cs @@ -9,6 +9,18 @@ namespace Logos.Utility.Tests [TestFixture] public class EnumerableUtilityTests { + [Test] + public void EmptyIfNullNull() + { + CollectionAssert.AreEqual(new int[0], ((IEnumerable) null).EmptyIfNull()); + } + + [Test] + public void EmptyIfNullNonNull() + { + CollectionAssert.AreEqual(new[] { 1, 2 }, (new[] { 1, 2 }).EmptyIfNull()); + } + const int NullInt = 1234567; [TestCase(new[] { 1, 2, 3, 4, 5 }, 15)]