When using a .NET type that isn't a framework type in String.Format, is it possible to define custom format strings for that type somewhere/somehow?
Consider the following LINQPad program:
void Main()
{
var t = new Test(DateTime.Now);
string.Format("{0}", t).Dump();
string.Format("{0:dd}", t).Dump();
}
public class Test
{
private readonly DateTime _DateTime;
public Test(DateTime dateTime)
{
_DateTime = dateTime;
}
public override string ToString()
{
return _DateTime.ToString();
}
public string ToString(string format)
{
return _DateTime.ToString(format);
}
public string ToString(string format, IFormatProvider provider)
{
return _DateTime.ToString(format, provider);
}
}
I want the second call to string.Format
there to format the value as the days of that internal date, but it still displays the full date and time, so the output of the program is at the time of testing:
30.08.2013 13:53:55
30.08.2013 13:53:55
Instead I would like this:
30.08.2013 13:53:55
30
Obviously string.Format
doesn't just use reflection to find my variants of .ToString
. Is there an interface I can implement? Must I implement some other type and register it somewhere to do this?
Is this even possible to achieve?
There is the IFormattable interface...
Probably you only have to implement it.
Try with
The
{0}
is passed asnull
, while the{0:xxx}
is passed asxxx