Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created November 22, 2025 18:17
Show Gist options
  • Select an option

  • Save karenpayneoregon/233e2c0d30313fd1e632462ba9c91e86 to your computer and use it in GitHub Desktop.

Select an option

Save karenpayneoregon/233e2c0d30313fd1e632462ba9c91e86 to your computer and use it in GitHub Desktop.
C# Ellipsis
public readonly struct EllipsisNumericFormattable<T> : IFormattable where T : struct, IFormattable
{
private readonly T _value;
private readonly int _width;
private readonly char _paddingChar;
public EllipsisNumericFormattable(T value, int width, char paddingChar)
{
_value = value;
_width = width;
_paddingChar = paddingChar;
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
// Apply numeric formatting first (e.g., format “C”)
string formatted = _value.ToString(format, formatProvider) ?? "";
// Then apply Ellipsis padding
return formatted.Ellipsis(_width, _paddingChar);
}
public override string ToString()
=> ToString(null, null);
}
public static class GenericExtensions
{
public static string Ellipsis<T>(this T sender, int width, char paddingChar = '.') where T : INumber<T>
=> sender.ToString().Ellipsis(width, paddingChar);
public static string Ellipsis<T>(this T? sender, int width, char paddingChar = '.') where T : struct
=> sender is not null ?
sender.ToString().Ellipsis(width, paddingChar) :
"".Ellipsis(width, paddingChar);
public static IFormattable EllipsisFormattable<T>(this T sender, int width, char paddingChar = '.')
where T : struct, IFormattable
=> new EllipsisNumericFormattable<T>(sender, width, paddingChar);
}
using Spectre.Console;
using SamplesApp.Classes.Extensions;
namespace SamplesApp;
internal partial class Program
{
static void Main(string[] args)
{
var products = MockedData.CreateProducts();
foreach (var p in products)
{
if (p.Price < 50)
{
AnsiConsole.MarkupLine($"[green]{p.Name.Ellipsis(15)}[/][yellow]{p.Price.EllipsisFormattable(15):C}on sale[/]");
}
else
{
AnsiConsole.MarkupLine($"[green]{p.Name.Ellipsis(15)}[/][cyan]{p.Price.EllipsisFormattable(15):C}not on sale[/]");
}
}
}
}
public class Product
{
public int Id { get; set; }
public required string Name { get; set; }
public decimal Price { get; set; }
}
public class MockedData
{
public static List<Product> CreateProducts()
=>
[
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Keyboard", Price = 49.50m },
new Product { Id = 3, Name = "Mouse", Price = 29.99m },
new Product { Id = 4, Name = "Monitor", Price = 199.00m },
new Product { Id = 5, Name = "Headphones", Price = 89.75m }
];
}
public static class StringExtensions
{
public static string Ellipsis(this string? sender, int width, char paddingChar = '.')
=> sender.PadRight(width, paddingChar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment