Helping you solve those tough coding problems!

C# Truncate String Extension C# Truncate String Extension

Published on Feb 28, 2019 by Jamie Munro

Leveraging C#'s substring to truncate a string, I am going to demonstrate how to create a string extension with a new re-usable function called Truncate.




Creating a String Extension



To truncate a string you would check its length, then use substring to limit it's length from 0 to the ideal length. This function will be a great addition to the previously created HasValue string extension class.

Common code to truncate a string would be as follows:


if (myString.Length > 30 ?)
   myString.Substring(0, 30);


This becomes quite cumbersome to repeat, so let's convert the above code into a string extension to increase both the readability and usability of it:


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


Using the Truncate String Extension



This code then can be implemented as follows:


var myString = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(myString.Truncate(10));


The output would then be: abcdefghij

Tags: ASP.NET | c# | truncate

My Books