Cool C# 3.0 Extension Method Idea

extension_cable
Extension Methods, simply put, allow for the extension of existing types (including the types you don't own) to include new methods. Insightful dialog can be found in several other places so I won't go there, but I did come up with an example that I thought might be useful. The Truncate method above truncates strings that are longer than maxLength and adds an ellipsis to indicate that the string has been truncated.  If the string is less than maxLength, the entire string is returned. The first argument in the method signature tells the compiler that this method is an extension method and adds the Truncate method to all instances of type string.  It is a simple matter to use the extension method, see the code below.


1.) Declare the Truncate extension method in a unique namespace (Don't use System!):

   1:  namespace PageBrooks.Extensions
   2:  {
   3:      public static class StringExtensions
   4:      {
   5:          public static string Truncate(this string s, int maxLength)
   6:          {
   7:              if (string.IsNullOrEmpty(s) || maxLength <= 0)
   8:                  return string.Empty;
   9:              else if (s.Length > maxLength)
  10:                  return s.Substring(0, maxLength) + "...";
  11:              else
  12:                  return s;
  13:          }
  14:      }
  15:  }

2.) Specify the namespace to which the extension method resides:

   1:  using PageBrooks.Extensions;

3.) Declare a string and use the extension method:

   1:  string test = "Robots are cool";
   2:  string testTruncated = test.Truncate(10); // Robots are...
Comments have been closed on this topic.