Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 12, 2013 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4774010 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4774010 to your computer and use it in GitHub Desktop.
IFormattable example
public class User : IFormattable
{
private int _age;
private string _name;
/// <summary>
/// Gets/sets the Name.
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets/sets the Age.
/// </summary>
public int Age
{
get { return _age; }
set { _age = value; }
}
/// <summary>
/// Object.ToString() implementation
/// </summary>
public override string ToString()
{
return string.Format("'{0}', age {1}", Name, Age);
}
/// <summary>
/// Just a format string, functionality you find in DateTime.Now.ToString()
/// </summary>
public string ToString(string format)
{
return ToString(format, null);
}
/// <summary>
/// IFormattable.ToString() implementation
/// </summary>
public string ToString(string format, IFormatProvider formatProvider)
{
// Default format
if (string.IsNullOrEmpty(format) || format == "G")
return string.Format("'{0}', age {1}", Name, Age);
if (format == "name")
return Name;
else if (format == "age")
return Age.ToString();
else
{
// The IFormattable example shows branching based on the format. This is fine if the class
// is being used with composite formatting, however to support the DateTime.Now.ToString("xxx")
// style formatting, we need the below.
string result = format;
result = result.Replace("name", Name);
result = result.Replace("age", Age.ToString());
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment