Created
February 12, 2013 22:22
-
-
Save yetanotherchris/4774010 to your computer and use it in GitHub Desktop.
IFormattable example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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