Skip to content

New string extension methods #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions ExtensionMethods/Strings/StringExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,74 @@ public static string SubstringAfter(this string string1, string string2)
return string.Empty;
}

/// <summary>
/// Returns the string as a boolean value
/// </summary>
/// <param name="str">
/// The string
/// </param>
/// <returns>
/// Boolean value
/// </returns>
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;
}

/// <summary>
/// Safely parse string to integer. Return zero if not an integer
/// </summary>
/// <param name="str">
/// The string
/// </param>
/// <returns>Integer Value</returns>
public static int ToInt(this string str)
{
int retValue = 0;
if (str != null)
int.TryParse(str, out retValue);

return retValue;
}

/// <summary>
/// Returns the string as a datetime
/// </summary>
/// <param name="str">
/// The string
/// </param>
/// <returns>
/// A DateTime value
/// </returns>
public static DateTime ToDate(this string str)
{
DateTime date;
DateTime.TryParse(str, out date);
return date;
}

/// <summary>
/// Returns the string as a nullable datetime
/// </summary>
/// <param name="str">
/// The string
/// </param>
/// <returns>
/// A nullable DateTime value
/// </returns>
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;
}
}
}