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

1 comment:

Smith said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.