CSCI 1301

ToString() Method

1. Learning Objectives

  • What is ToString() method
  • How to use format specifiers with ToString() method
  • How to override ToString() method

2. What is ToString() Method

In C#, every object and every simple variable has a ToString() method. It converts an object to its string representation so that it is suitable for display on the screen.

3. Syntax

You can call the ToString() method of any object or variable using the following syntax:

1// object ToString()
2objName.ToString();
3
4// any variable ToString()
5variableName.ToString();
6
7// or in general
8identifier.ToString();

This example shows how to display string value of a numeric variable:

1// you can call ToString() on any variable
2
3double number = 5.4d;
4Console.WriteLine(number.ToString());

If you omit explicit method call, ToString() will get called implicitly when you try to display something on the screen:

1// this will call ToString() method even when
2// we do not explicitly type .ToString()
3
4Console.WriteLine(objName);

4. Other Users

ToString() method also helps in scenarios where we want to concatenate string type with a non-string type:

1string result = "I'm a string " + 5;
2Console.WriteLine(result);

In the example above, ToString() method of the integer literal 5 will get called automatically, converting it to string type prior to concatenation operation. Note that this automatic type conversion is specific to C# programming language. This is not always the case for all languages. For example if you are familiar with Python language, it requires explicitly converting numeric type to string before concatenation.

5. Format Specifiers

ToString() method is helpful in scenarios where we want to format numeric types to display using specific format. Then we provide a format specifier as an argument to the ToString() method.

Here "N2" is a format specifier.

1// display value with exactly 2 decimal places
2
3double number = 5.4d;
4Console.WriteLine(number.ToString("N2"));

List of Common Format Specifiers

These are some commonly used format specifiers

inputDescription
N0numeric format, 0 decimal precision
N1numeric format, 1 decimal precision
N2numeric format, 2 decimal precision .. etc
Pwill format number as a percentage e.g. 50.5%
Ccurrency format specifier e.g $1.50

For a complete reference, see list of format specifiers.

Format Specifiers with String Interpolation

If you are using string interpolation syntax instead of ToString(), you can use format specifiers by adding colon : after a variable, then specify the output format.

1// format specifiers with string interpolation
2
3double number = 5.4d;
4Console.WriteLine($"Value of number is {number:N2}");

6. Exercise: Format Specifiers

Experiment with the code below to understand how to use format specifiers.

7. Overriding ToString() Method

Whenever you create a class in C#, that class has a ToString() method. It is not visible in the class, but nonetheless it is already defined for the class. The default ToString() method for a class is not particularly informative. It displays the name of the class:

Whenever you create a custom class, you should override the ToString() method to provide more meaningful information about the instance. This is helpful when debugging the code as it reveals more information about object and its instance variables.

Syntax

To override the default ToString() method of a class, use the following syntax

SomeClass.cs
1public class SomeClass{
2
3 // ... other class members ...
4
5 public override string ToString(){ // this line exactly
6
7 // implementation here!
8 // this method MUST return a string
9 return "Custom ToString()";
10
11 }
12}

Pay attention to the following:

  • Access modifier MUST be public
  • MUST write keyword override after the access modifier this keyword tells the compiler to use our version over the default implementation
  • Return type MUST be string it is always a string. Recall from a before that when specifying string return type, we must also return a string in the method body.
  • Method name must be ToString() - no parameters, and the letter case must match

In general, when you want to override a C# method, the signature must match exactly with the method you want to override.

Sample Code With ToString Override

The next example shows a completed implementation of a custom ToString() method within a class (lines 13 - 15). When you execute the code, you can also see that instead of just displaying the class name, we can now see much more useful information about the specific object and its properties.

For exercise you can try modifying the code to display age before name.


8. Summary

What is ToString() method?

Method that returns a string representation of a type.

How to use format specifiers with ToString() method

Format specifiers enable displaying values is a systematic way, for example as currency. You can use format specifiers with ToString() method by passing the format specifier as an argument, for example:

1// this command outputs 50.00 %
2Console.WriteLine ((0.5).ToString("P"));

How to override ToString() method

Overriding requires using this syntax where the method signature must match exactly. The method must return a string value.

1public override string ToString(){
2 return "Your string value here";
3}