You can create custom format provider
public class TelephoneFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
var numericString = arg.ToString();
if (format != "###-###-####")
return String.Format(format, arg);
if (numericString.Length <= 3)
return numericString;
if (numericString.Length <= 6)
return numericString.Substring(0, 3) + "-" + numericString.Substring(3, numericString.Length - 3);
if (numericString.Length <= 10)
return numericString.Substring(0, 3) + "-" +
numericString.Substring(3, 3) + "-" + numericString.Substring(4, numericString.Length - 6);
throw new FormatException(
string.Format("'{0}' cannot be used to format {1}.",
format, arg));
}
}
After this you can use it
public static void Test()
{
Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 0));
Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 911));
Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 12346));
Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 8490216));
Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 4257884748));
}
I hope it will help you.
Result
0
911
123-46
849-021-2
425-788-8847