Home > database >  How to control C# string interpolation formatting for classes
How to control C# string interpolation formatting for classes

Time:05-17

This works:

class Item
{
    public decimal Number { get; set; }
    public override string ToString() => Number.ToString();
}

then later:

var item = new Item() { Number = 12m };
Console.WriteLine($"Item: {item}");

prints

Item: 12

But what I really want to do instead is:

Console.WriteLine($"Item: {item:C2}");

And somehow get

Item: $12.00

Anyone know if/how this could be done?

Thanks!

CodePudding user response:

You can implement IFormattable (docs):

class Item : IFormattable
{
    public decimal Number { get; set; }
    public override string ToString() => Number.ToString();

    // IFormattable's .ToString method:    
    public string ToString(string format, IFormatProvider formatProvider) => Number.ToString(format, formatProvider);
}

Now this code will work:

Console.WriteLine($"Item: {item:C2}");

In this case it should work perfectly since you're basically proxying the same method on decimal, but if you're going to do anything more complicated, you should probably read the docs linked above, especially the Notes to Implementers section.

  •  Tags:  
  • c#
  • Related