Question

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?

Was it helpful?

Solution

There is the IFormattable interface...

class MyObject : IFormattable
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        throw new NotImplementedException();
    }
}

Probably you only have to implement it.

The IFormattable interface converts an object to its string representation based on a format string and a format provider.

Try with

class Foo : IFormattable
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        return string.Format("Foo formatted as {0}", format != null ? format : "(null)");
    }
}

Console.WriteLine("{0}, {0:xxx}", new Foo());

The {0} is passed as null, while the {0:xxx} is passed as xxx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top