Friday, March 14, 2014

Really? there is no String.Truncate in C#...? so here is one...

  public static class StringExtension
  {
      public static string Truncate(this string originalString, int maxSize)
      {
         // check for null
         if (String.IsNullOrEmpty(originalString))
         {
            // return original
            return originalString;
         }

         // validate the size
         if (maxSize < 0)
         {
            throw new ApplicationException("Invalid maxSize for Truncating a string, value must be positive or zero");
         }

         if (originalString.Length > maxSize)
         {
            // trim it
            return originalString.Substring(0, maxSize);
         }
         else
         {
            // return the original
            return originalString;
         }
      }
   }
And the client code will look like this:
         string foo = "1234567890";
         string newString = foo.Truncate(4);

No comments: