We have a lot of confortable methods ready to use in our .NET objects and this is wonderful: just think for example the method .toString()! How much do we use it? But, sometimes, these methods aren’t enough and we need to create others on our own.

In this post I show how to create an extesion method useful to truncate a string if it is too long for us.

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

Note:

  1. The class has to be static (or shared in VB.NET)
  2. Also the method has to be static (or shared in VB.NET)
Advertisements