How do I truncate a .NET string?

There isn’t a Truncate() method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don’t have to duplicate it everywhere:

public static class StringExt
{
    public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? value : value.Substring(0, maxLength); 
    }
}

Now we can write:

var someString = "...";
someString = someString.Truncate(2);
2021-09-17 Alternative with suffix and c#8 nullable reference types.
public static class StringExt
{
    public static string? Truncate(this string? value, int maxLength, string truncationSuffix = "…")
    {
        return value?.Length > maxLength
            ? value.Substring(0, maxLength) + truncationSuffix
            : value;
    }
}

To write:

"abc".Truncate(2);          // "ab…"
"abc".Truncate(3);          // "abc"
((string)null).Truncate(3); // null

Leave a Comment