I’ll start this library with the easiest thing to add into it, string extensions. To show an example, I’ll add an extension method called ToInt32. This method converts a string to an integer. If the string is an invalid integer it will return a value of default(int) or another value if provided.
For example, we have: string strNum = “33”;
Before extension:
int num; int.TryParse( strNum, out num );
After extension:
int num = strNum.ToInt32(); // invalid string returns default(int) int num = strNum.ToInt32( 0 ); // invalid string returns 0
Convert an string to a 32-bit integer
public static int ToInt32(this object source, int def = default(int) ) { int target = def; if ( source is string ) target = IntParse( source.ToString() ); else if ( source is int ) target = (int)source; return target; }
Trim white space
public static string TrimWhiteSpace( this string source ) { if ( string.IsNullOrEmpty( source ) ) return string.Empty; return source.Trim(); }
Test equality between two string ignoring case.
static public bool NotEqualIgnoreCase( this string source, string val ) { if ( string.IsNullOrEmpty(source) && !string.IsNullOrEmpty( val ) ) return true; if ( string.IsNullOrEmpty( val ) ) return true; return !string.Equals( source, val, StringComparison.OrdinalIgnoreCase ); }
Test equality between two string ignoring case.
static public bool EqualsIgnoreCase( this string source, string val ) { if ( string.IsNullOrEmpty( source ) && !string.IsNullOrEmpty( val ) ) return false; if ( string.IsNullOrEmpty( val ) ) return false; return string.Equals( source, val, StringComparison.OrdinalIgnoreCase ); }
Returns a value indicating whether the specified String object occurs within this string ignoring case, uses StringComparison.OrdinalIgnoreCase
static public bool ContainsIgnoreCase( this string source, string val ) { if ( string.IsNullOrEmpty( source ) || string.IsNullOrEmpty( val ) ) return false; return source.IndexOf( val, StringComparison.OrdinalIgnoreCase ) >= 0; }
Takes a string and if its length is greater than maxLen it trims it to maxLen-3 and appends three periods to the string.
static public string ToEllipsis( this string source, int maxLen ) { if ( string.IsNullOrEmpty( source ) ) return string.Empty; maxLen -= 3; if ( source.Length > maxLen ) return string.Format( "{0}...", source.Substring( 0, maxLen ) ); return source.TrimEnd(); }
Here’s some other methods I’ve added, mainly for overall code readability. I think it’s easier to read str.IsNotNullOrEmpty() vs !string.IsNullOrEmpty(str);.
- IsNullOrEmpty
- IsNotNullOrEmpty
- ToInt16
- ToInt64