From 74c84652063001dc67536b85e75a73803be62af5 Mon Sep 17 00:00:00 2001 From: bjarnef Date: Sun, 21 Feb 2016 20:22:43 +0100 Subject: [PATCH] New string extension methods ToBoolean(), ToInt(), ToDate(), ToNullableDate() --- .../Strings/StringExtensionMethods.cs | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) 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; + } } }