What method in the String class returns only the first N characters?

public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str)) return str;

    return str.Substring(0, Math.Min(str.Length, maxLength));
}

In C# 8 or later it is also possible to use a Range to make this a bit terser:

public static string TruncateLongString(this string str, int maxLength)
{
    return str?[0..Math.Min(str.Length, maxLength)];
}

Which can be further reduced using an expression body:

public static string TruncateLongString(this string str, int maxLength) =>
    str?[0..Math.Min(str.Length, maxLength)];

Note null-conditional operator (?) is there to handle the case where str is null. This replaces the need for an explict null check.

Leave a Comment