All String Formatting in C#: Unlocking the Power of “To String()”

Amit Prajapati
3 min readJul 24, 2024

In C#, the ToString() method is a versatile function used to convert objects to their string representation. By using format strings, developers can precisely control how values are represented, whether they are numbers, dates, or custom objects. In this post, we’ll explore the power of ToString() and some of its common applications.

The Basics of ToString()

The ToString() method is defined in the base Object class, which means it can be used on any object in C#. When called without parameters, it returns a string that represents the current object. However, its true power is revealed when using format strings.

Common Format Specifiers

Decimal Format Specifier: ToString(“D4”)

The “D” format specifier stands for “Decimal” and is used with integer types. The number following “D” indicates the minimum number of digits to include, padding with leading zeros if necessary.

int number = 42;
Console.WriteLine(number.ToString("D4"));
// Outputs: 0042

Currency Format Specifier: ToString(“C0”)

The “C” format specifier stands for “Currency”. It formats the number as a currency value, and the number following “C” indicates the number of…

--

--

Amit Prajapati

I am Technical Consultant from Mumbai, India. I like to contribute my knowledge to the community and good social cause.