Sealed Modifier on Record ToString
- You can add the sealed modifier when you override ToString in a record type.
- Sealing the ToString method prevents the compiler from synthesizing a ToString method for any derived record types.
- A sealed ToString ensures all derived record types use the ToString method defined in a common base record type and have a consistent string representation throughout a hierarchy of
record
types. - Derived records will still have a
PrintMembers
method generated for all derived properties.
Compiler Generated ToString and PrintMembers
The compiler synthesizes a virtual PrintMembers method and a ToString override to display the names and values of public properties and fields.
public record Person(string FirstName, string LastName, string[] PhoneNumbers);
Person person1 = new("George", "Washington", new string[] {"123456789"});
Console.WriteLine(person1);
//Output - Person { FirstName = George, LastName = Washington, PhoneNumbers = System.String[] }
Derived Records
public abstract record Person(string FirstName, string LastName);
public record Teacher(string FirstName, string LastName, int Grade)
: Person(FirstName, LastName);
public record Student(string FirstName, string LastName, int Grade)
: Person(FirstName, LastName);
public static void Main()
{
Person teacher = new Teacher("Nancy", "Davolio", 3);
Console.WriteLine(teacher);
// output: Teacher { FirstName = Nancy, LastName = Davolio, Grade = 3 }
}
Sealed ToString Method
ToString
method is sealed in Person record. Derived record like Teacher
can't override
public abstract record Person(string FirstName, string LastName)
{
public sealed override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Base Record"); // type name
stringBuilder.Append(" { ");
if (PrintMembers(stringBuilder))
{
stringBuilder.Append(" ");
}
stringBuilder.Append("}");
return stringBuilder.ToString();
}
}
public record Teacher(string FirstName, string LastName, int Grade): Person(FirstName, LastName)
{
//Compiler error
//Cannot override
public override string ToString()
{
}
}