Archive for the ‘CodeSnippet’ Category
Silly formatter
Why use padleft, when you can use formatters?!!!
private void button1_Click(object sender, System.EventArgs e)
{
string a = "aaa";textBox1.Text = String.Format(new SillyFormat(), "{0:Z10}", a) ;
}
private void Dummy_Load(object sender, System.EventArgs e)
{
}
public class SillyFormat : IFormatProvider, ICustomFormatter
{
public object GetFormat (Type service)
{
if (service == typeof (ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format (string format, object arg, IFormatProvider provider)
{
if (arg == null)
{
throw new ArgumentNullException("Please provide argument to format.");
}
if (format != null && arg is string)
{
string s = format.Trim().ToLower();
string ret = (string) arg;
if (s.StartsWith("z"))
{
format = format.Trim (new char [] {'Z'});
int pos = Convert.ToInt32( format ) - ret.Length;
if ( pos > 0 )
{
ArrayList items = ArrayList.Repeat("0", Convert.ToInt32( format ) - ret.Length);
items.Add(ret);
string[] strings = (string[]) items.ToArray(typeof(String));
ret = String.Join("",strings);
}
}
return ret;
}
else if (arg is IFormattable)
{
return ((IFormattable)arg).ToString(format, provider);
}
else
{
return arg.ToString();
}
}
}