Clamping a strings length in C#
Oct 23, 2023 /
# C#
The Clamp
extension method will limit a string to a certain amount of max characters. Adds ellipses if the string is > max characters.
Great when you have a long string, like a blog post, and want to show a preview of it without showing the full thing.
public static string Clamp(this string value, int maxChars)
{
return value.Length <= maxChars
? value
: value.Substring(0, maxChars) + "...";
}
// example usage
var str = "This is some long sentence";
var clampedStr = str.Clamp(10);
// clampedStr = "This is so...";