diff --git a/ExtensionMethods/Strings/StringExtensionMethods.cs b/ExtensionMethods/Strings/StringExtensionMethods.cs index 830be9a..7adf7f6 100644 --- a/ExtensionMethods/Strings/StringExtensionMethods.cs +++ b/ExtensionMethods/Strings/StringExtensionMethods.cs @@ -340,6 +340,74 @@ public static string SubstringAfter(this string string1, string string2) return string.Empty; } + /// + /// Returns the string as a boolean value + /// + /// + /// The string + /// + /// + /// Boolean value + /// + public static bool ToBoolean(this string str) + { + if (string.IsNullOrEmpty(str)) + return false; + if (str == "1") + return true; + bool value; + return bool.TryParse(str, out value) && value; + } + /// + /// Safely parse string to integer. Return zero if not an integer + /// + /// + /// The string + /// + /// Integer Value + public static int ToInt(this string str) + { + int retValue = 0; + if (str != null) + int.TryParse(str, out retValue); + + return retValue; + } + + /// + /// Returns the string as a datetime + /// + /// + /// The string + /// + /// + /// A DateTime value + /// + public static DateTime ToDate(this string str) + { + DateTime date; + DateTime.TryParse(str, out date); + return date; + } + + /// + /// Returns the string as a nullable datetime + /// + /// + /// The string + /// + /// + /// A nullable DateTime value + /// + public static DateTime? ToNullableDate(this string str) + { + if (string.IsNullOrEmpty(str)) + return null; + DateTime date; + if (DateTime.TryParse(str, out date)) + return date; + return null; + } } }