From 080a5c0f2de45ca4407976a8fb1af974fd064e0f Mon Sep 17 00:00:00 2001 From: Michael Becker Date: Fri, 4 Dec 2020 23:42:30 -0500 Subject: [PATCH] fix bug in TryParse - needed to specify MakeByRefType(), pass through the return value from the array --- MBS.Framework/StringExtensions.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/MBS.Framework/StringExtensions.cs b/MBS.Framework/StringExtensions.cs index 7e26218..493df72 100644 --- a/MBS.Framework/StringExtensions.cs +++ b/MBS.Framework/StringExtensions.cs @@ -55,6 +55,13 @@ namespace MBS.Framework return (T)Parse(value, typeof(T)); } + public static T TryParse(this string value, T defaultValue = default(T)) + { + if (TryParse(value, typeof(T), out object output)) + return (T)output; + return defaultValue; + } + /// /// Parses the given with the specified 's public static Parse() method. If no such method exists, @@ -67,6 +74,7 @@ namespace MBS.Framework { return TryParse(value, type, value, out output); } + /// /// Parses the given with the specified 's public static Parse() method. If no such method exists, /// returns . @@ -77,12 +85,14 @@ namespace MBS.Framework /// Default value. public static bool TryParse(this string value, Type type, object defaultValue, out object output) { - System.Reflection.MethodInfo miParse = type.GetMethod("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, System.Reflection.CallingConventions.Any, new Type[] { typeof(string), type }, null); + System.Reflection.MethodInfo miParse = type.GetMethod("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new Type[] { typeof(string), type.MakeByRefType() }, null); if (miParse != null) { // the given type implements a public static Parse(String) method, so use it object retval = null; - bool ret = (bool)miParse.Invoke(null, new object[] { value, retval }); + object[] parms = new object[] { value, retval }; + bool ret = (bool)miParse.Invoke(null, parms); + retval = parms[1]; if (ret) { output = retval;