Skip to content

Instantly share code, notes, and snippets.

Created August 18, 2010 07:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/533905 to your computer and use it in GitHub Desktop.
Save anonymous/533905 to your computer and use it in GitHub Desktop.
public sealed class PaddedStringFormatInfo : IFormatProvider, ICustomFormatter {
public object GetFormat(Type formatType)
{
if (typeof(ICustomFormatter).Equals(formatType)) return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg == null)
throw new ArgumentNullException("Argument cannot be null");
string[] args;
if (format != null)
args = format.Split(':');
else
return arg.ToString();
if (args.Length == 1)
String.Format("{0, " + format + "}", arg);
int padLength = 0;
if (!int.TryParse(args[0], out padLength))
throw new ArgumentException("Padding lenght should be an integer");
switch (args.Length)
{
case 2://Padded format
if (padLength > 0)
return (arg as string).PadLeft(padLength, args[1][0]);
return (arg as string).PadRight(padLength * -1, args[1][0]);
default://Use default string.format
return string.Format("{0," + format + "}", arg);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment