C Sharp

How to truncate a string using C#

C# does not have a default truncate method. What you can do is write a static method and then use it everywhere within your codebase.

public static string Truncate(this string value, int maxLength) 
   if (string.IsNullOrEmpty(value)) return value; 
   return value.Substring(0, Math.min(value.Length, maxLength)); 

Once this is implemented, you can simply truncate strings like:

var hello = "worldworldworld" 
hello.Truncate(5) //Outputs: "world"

Leave a Reply