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
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 objectStudent student1 = new("Sam", "Johnson") { Marks = 100 };// display objectConsole.WriteLine(student1.ToString());Console.WriteLine(student1);}}
Student { FirstName = Sam, LastName = Johnson, Marks = 100 }
Student { FirstName = Sam, LastName = Johnson, Marks = 100 }
Free Resources