Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

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

Ayesha Naeem

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring