Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created March 16, 2025 16:26
Show Gist options
  • Save karenpayneoregon/a6aa0304b7c271846c62db7f633aad97 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/a6aa0304b7c271846c62db7f633aad97 to your computer and use it in GitHub Desktop.
Record PrintMembers custom

This is an example of using PrintMembers on records to control the output of a record and hide the value of the BirthDate property.

public record Person(string FirstName, string LastName, DateOnly BirthDate, string[] PhoneNumbers)
{
protected virtual bool PrintMembers(StringBuilder sb)
{
sb.Append($"FirstName = {FirstName}, LastName = {LastName}, Birth = {BirthDate:MM/dd/yyyy}");
if (!(PhoneNumbers?.Length > 0)) return true;
sb.Append(", PhoneNumbers: ");
sb.Append(string.Join(", ", PhoneNumbers));
sb.Append("");
return true;
}
public override string ToString()
{
var builder = new StringBuilder();
(this with { BirthDate = default }).PrintMembers(builder);
return builder.ToString();
}
}
public static class PersonExtensions
{
/// <summary>
/// Enhances the string representation of a <see cref="Person"/> object
/// by applying color formatting to its property names using NuGet package Spectre.Console.
/// </summary>
/// <param name="person">The <see cref="Person"/> instance to be colorized.</param>
/// <returns>A string representation of the <paramref name="person"/> object
/// with colorized property names.</returns>
public static string Colorize(this Person person) =>
person.ToString()
.Replace("FirstName", "[cyan]FirstName[/]")
.Replace("LastName", "[cyan]LastName[/]")
.Replace("Birth", "[cyan]Birth[/]")
.Replace("PhoneNumbers", "[cyan]Phone Numbers[/]");
}
using System.Text;
namespace WorkingWithRecords;
internal partial class Program
{
private static void Main(string[] args)
{
var person = new Person(
"Karen", "Payne",
new DateOnly(1956, 9, 24),
["123-4567", "987-6543", "555-7890"]);
AnsiConsole.MarkupLine(person.Colorize());
var (firstName, lastName, _, _) = person;
AnsiConsole.MarkupLine($"[cyan]First Name:[/] {firstName} [cyan]Last Name:[/] {lastName}");
Console.WriteLine();
AnsiConsole.MarkupLine("[yellow]Done[/]");
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment