0

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!

3
  • This isn't specific to string interpolation as Console.WriteLine($"Item: {item:C2}"); is the same as Console.WriteLine("Item: {0:C2}", item); is the same as Console.WriteLine("Item: " + item.ToString("C2")); (when such an overload is defined). Also, if what you want is item's Number formatted as currency then you can ask for that specifically: Console.WriteLine($"Item: {item.Number:C2}"); Commented May 17, 2022 at 2:28
  • Right, I wanted to keep the code concise, and "Number" is really an implementation detail in my case that I wanted to hide. Making it public was the quickest way to explain the problem, but in real life, I want to be able to change the underlying backing scheme as needed. Commented May 17, 2022 at 4:06
  • Reference docs Commented May 17, 2022 at 13:18

1 Answer 1

5

$"{item:C2}" effectively calls item.ToString("C2", CultureInfo.CurrentCulture);, so 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, this is exactly what I needed. Just couldn't figure out the right way to web search for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.