Extension Methods make life easier (C#)

I use extension methods when I remember they exist.  I started getting tired of writing code to check strings for Null, Empty, Equal before using a database column when I remembered Extension Methods are there to make life easier!  Some great articles/blog entries on it can be found at:

In a nutshell I found myself writing code that looks like:

   1:  if (!string.IsNullOrEmpty(details.FeedSourceTable) && details.FeedSourceTable.Equals("auto", StringComparison.CurrentCultureIgnoreCase))
   2:  {
   3:  }

After creating a (simple) string extension method I now have code that looks like:

   1:  if (details.FeedSourceTable.IsNotNullEmptyAndEquals("auto", StringComparison.CurrentCultureIgnoreCase))
   2:  {
   3:  }

To accomplish this I added a new class, ExtensionsString, to my root library (Sol3.dll) and added the extension methods to it.  The class looks like:

   1:  using System;
   2:   
   3:  namespace Sol3
   4:  {
   5:      public static class ExtensionsString
   6:      {
   7:          public static bool IsNullOrEmpty(this string source)
   8:          {
   9:              return string.IsNullOrEmpty(source);
  10:          }
  11:          public static bool IsNotNullEmptyAndEquals(this string source, string target)
  12:          {
  13:              if (!string.IsNullOrEmpty(source) && source.Equals(target))
  14:                  return true;
  15:              else
  16:                  return false;
  17:          }
  18:          public static bool IsNotNullEmptyAndEquals(this string source, string target, StringComparison compareOption)
  19:          {
  20:              if (!string.IsNullOrEmpty(source) && source.Equals(target, compareOption))
  21:                  return true;
  22:              else
  23:                  return false;
  24:          }
  25:      }
  26:  }

The key parts to understand while writing Extension Methods:

  1. The class has to be static (in VB it would be a Module instead)
  2. The Class name should not be a duplicate of another class name (hopefully this is obvious)
  3. The first parameter must include the keyword this followed by the data type to extend.  (Line 7, 11 and 18 illustrate this)

I won’t go into to much more detail as the 2 links I gave at the beginning of this blog entry have more than enough info.  Scott Mitchell’s article also has a VB example.

1 Comment

  • I'm a recent ocnvert from Java and extension methods are one of my favorite things about .NET! It makes dealing with someone else's legacy code or third party library that you can't change a heck of a lot easier! It also means that different uses of a component can add their own local extension methods rather than trying to make that shared component please everyone's needs.

Comments have been disabled for this content.