Trusted answers to developer questions

What is built-in formatting for display in C# 9.0?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The compiler-generated ToString() method in C# record types displays the public fields and properties with their names and values.

For example, for a record Person that contains FirstName and LastName as public properties, the ToString method will display the properties in the following format.

Person { FirstName = Tom, LastName = Sawyer }

The compiler creates a virtual PrintMembers method and overrides the ToString method with the help of a StringBuilder object to implement the built-in formatting functionality.

Example

The following example demonstrates how the built-in formatting display is used in C# records.

The program creates a record type Student and initializes its properties. It then uses the ToString() method to display the object’s properties with names and values. Simply writing the object’s name as the parameter to the WriteLine function yields identical results.

using System;
public class Program
{
public record Student(string FirstName, string LastName)
{
public int Marks { get; init; }
}
public static void Main()
{
// create an object
Student student1 = new("Sam", "Johnson") { Marks = 100 };
// display object
Console.WriteLine(student1.ToString());
Console.WriteLine(student1);
}
}

Output

Student { FirstName = Sam, LastName = Johnson, Marks = 100 }
Student { FirstName = Sam, LastName = Johnson, Marks = 100 }

RELATED TAGS

c#

CONTRIBUTOR

Ayesha Naeem
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?