Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active September 22, 2024 15:25
Show Gist options
  • Save karenpayneoregon/973b6eaf838eb8f8a75f025867898a21 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/973b6eaf838eb8f8a75f025867898a21 to your computer and use it in GitHub Desktop.
C# IFormattable example
public record Customer(int Id, string FirstName, string LastName, DateOnly BirthDay) : IFormattable
{
public int Id { get; set; } = Id;
public string FirstName { get; set; } = FirstName;
public string LastName { get; set; } = LastName;
public DateOnly BirthDay { get; set; } = BirthDay;
public string ToString(string format, IFormatProvider _)
=> format switch
{
"F" => $"{Id,-5}{FirstName} {LastName}",
"N" => $"{FirstName} {LastName}",
"B" => $"{BirthDay}",
"I" => $"{Id}",
_ => $"{Id,-5}{BirthDay} {LastName}, {BirthDay}"
};
/// <summary>
/// Stock version of ToString which returns the full name and age
/// </summary>
public override string ToString()
=> $"{FirstName} {LastName}, age {BirthDay.GetAge()}";
internal void Deconstruct(out string firstName, out string lastName, out DateOnly birth)
{
firstName = FirstName;
lastName = LastName;
birth = BirthDay;
}
}
public static class DateOnlyExtensions
{
public static int GetAge(this DateOnly dateOfBirth)
{
var (nYear, nMonth, nDay) = DateTime.Today;
var a = (nYear * 100 + nMonth) * 100 + nDay;
var (bYear, bMonth, bDay) = dateOfBirth;
var b = (bYear * 100 + bMonth) * 100 + bDay;
return (a - b) / 10000;
}
}
internal partial class Program
{
static void Main(string[] args)
{
Customer customer =
new(1,"Karen", "Payne",
new DateOnly(1956,9,24));
Console.WriteLine($"{customer:F}");
Console.WriteLine($"{customer:N}");
Console.WriteLine($"{customer:B}");
Console.WriteLine($"{customer:I}");
Console.WriteLine($"{customer}");
Console.WriteLine($"{customer.ToString()}");
var (firstName, lastName, birthDate) = customer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment