From ab2fc3fef9f64033f2c0c013675bc48615bca14f Mon Sep 17 00:00:00 2001 From: Ben Dixon Date: Wed, 6 Sep 2017 14:08:55 +0100 Subject: [PATCH] Avoid allocating in IsNotNullOrWhiteSpace check Fixes #1 --- src/Argument/Argument.cs | 9 +++++++-- .../ArgumentIsNotNullOrWhitespaceTests.cs | 10 +++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Argument/Argument.cs b/src/Argument/Argument.cs index a68e6cb..87c8adf 100644 --- a/src/Argument/Argument.cs +++ b/src/Argument/Argument.cs @@ -79,10 +79,15 @@ public static void IsNotNullOrWhiteSpace(string argument, string paramName) throw new ArgumentException("Value cannot be empty.", paramName); } - if (argument.Trim().Length == 0) + for (int i = 0; i < argument.Length; i++) { - throw new ArgumentException("Value cannot be white space.", paramName); + if (!char.IsWhiteSpace(argument[i])) + { + return; + } } + + throw new ArgumentException("Value cannot be white space.", paramName); } /// diff --git a/test/Argument.Test/ArgumentIsNotNullOrWhitespaceTests.cs b/test/Argument.Test/ArgumentIsNotNullOrWhitespaceTests.cs index 08e77e5..bbed0d0 100644 --- a/test/Argument.Test/ArgumentIsNotNullOrWhitespaceTests.cs +++ b/test/Argument.Test/ArgumentIsNotNullOrWhitespaceTests.cs @@ -6,12 +6,16 @@ namespace Enable.Common { public class ArgumentIsNotNullOrWhiteSpaceTests { - [Fact] - public void IsNotNullOrWhiteSpace_DoesNotThrowIfArgumentNotNullOrWhiteSpace() + [Theory] + [InlineData("foo")] + [InlineData("foo bar")] + [InlineData(" foo bar")] + [InlineData("foo bar ")] + [InlineData(" foo bar ")] + public void IsNotNullOrWhiteSpace_DoesNotThrowIfArgumentNotNullOrWhiteSpace(string argument) { // Arrange var fixture = new Fixture(); - string argument = fixture.Create(); try {