Follow @endyourif rss Facebook LinkedIn

C# Truncate String Extension C# Truncate String Extension

Published on Feb 28, 2019

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";

The output would then be: abcdefghij

Tags: ASP.NET MVC and Web API Tutorial | c# | truncate

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP