From e680bdb4b5d160362c3826a8a400ffc7b2119686 Mon Sep 17 00:00:00 2001 From: mdodkins Date: Tue, 21 Nov 2023 20:21:59 +0000 Subject: [PATCH] fix: Adds boolean support for Server.TryParse (#1605) --- .../Tests/Utilities/TryParseTests.cs | 23 +++++++++++++++++++ Projects/UOContent/Utilities/Types.cs | 11 +++++++++ 2 files changed, 34 insertions(+) create mode 100644 Projects/UOContent.Tests/Tests/Utilities/TryParseTests.cs diff --git a/Projects/UOContent.Tests/Tests/Utilities/TryParseTests.cs b/Projects/UOContent.Tests/Tests/Utilities/TryParseTests.cs new file mode 100644 index 0000000000..ab1d7aa9ad --- /dev/null +++ b/Projects/UOContent.Tests/Tests/Utilities/TryParseTests.cs @@ -0,0 +1,23 @@ +using Server; +using System; +using Xunit; + +namespace Server.Tests.Utility; + +public class TryParseTests +{ + [Theory] + [InlineData("True", null, true)] + [InlineData("False", null, false)] + [InlineData("Alakazam", "Not a valid boolean string.", true)] + public void TestTryParseBool(string value, string returned, bool parsedAs) + { + string actualReturned = Server.Types.TryParse(typeof(bool), value, out object constructed); + Assert.Equal(returned, actualReturned); + + if (returned == null) + { + Assert.Equal(parsedAs, constructed); + } + } +} diff --git a/Projects/UOContent/Utilities/Types.cs b/Projects/UOContent/Utilities/Types.cs index e04cd04623..faf482a6c3 100644 --- a/Projects/UOContent/Utilities/Types.cs +++ b/Projects/UOContent/Utilities/Types.cs @@ -187,6 +187,17 @@ public static string TryParse(Type type, string value, out object constructed) return null; } + if (IsType(type, OfBool)) + { + if (bool.TryParse(value, out bool parsed)) + { + constructed = parsed; + return null; + } + + return "Not a valid boolean string."; + } + if (value.StartsWithOrdinal("0x") && IsNumeric(type)) { try