Here I am going to post some of Frequently used extension methods which can be used with a string variable
/// <summary> /// It formats strings into a name format. /// </summary> /// <param name="firstname"></param> /// <param name="middlename"></param> /// <param name="lastname"></param> /// <returns></returns> public static String ToName(this String firstname, string middlename, string lastname) { if (!string.IsNullOrEmpty(lastname)) { return String.Format("{0} {1} {2}", firstname, middlename, lastname); } else { return firstname; } }
/// <summary> /// It formats string into a phone format /// </summary> /// <param name="phonenumber"></param> /// <returns></returns> public static string ToPhone(this string phonenumber) { if (phonenumber == null || phonenumber.Length == 0) return null; long pn = long.Parse( phonenumber.Replace(" ", string.Empty).Replace(",", string.Empty).Replace("(", string.Empty).Replace (")", string.Empty).Replace("-", string.Empty)); if (pn == 0) { return string.Empty; } else if (pn.ToString().Length == 10) { return String.Format("{0:(000) 000-0000}", pn); } else if (pn.ToString().Length == 7) { return String.Format("{0:000-0000}", pn); } else { return string.Empty; } }
/// <summary> /// It formats a string into SSN /// </summary> /// <param name="ssn"></param> /// <returns></returns> public static string ToSSN(this string ssn) { if (ssn == null || ssn.Length == 0) return null; long data = long.Parse( ssn.Replace(" ", string.Empty).Replace(",", string.Empty).Replace("(", string.Empty).Replace(")", string. Empty) .Replace("-", string.Empty)); return String.Format("{0:000-00-0000}", data); }
public static bool IsValidDate(this string inStr) { bool isValidDate = false; if (inStr != null) { isValidDate = inStr.Trim().Length > 0; DateTime dt; if (isValidDate) { isValidDate = DateTime.TryParse(inStr,out dt); } } return isValidDate; }
public static string ToZipCode(this string instr) { if (instr != null) { instr = instr.PadRight(9, '0'); return instr.Substring(0, 5) + "-" + instr.Substring(5, 4); } return string.Empty; }
/// <summary> /// It formats string into ToCurrency. /// </summary> /// <param name="inStr"></param> /// <returns></returns> public static string ToCurrency(this Decimal inStr) { return String.Format(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"),"{0:C}", inStr); }
No comments:
Post a Comment