Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.