For Microsoft Kool-Aid Drinkers, Non-paid MS Evangelists written by a Senior Consultant, Passionate about Tech

C# Tips and Tricks: Extension Methods

Ever wish you had a way to pad a string with spaces or multiply a number by 2 or 3 without having to write out all the syntax every time you needed it?  What if strings or integers just had functions built in to do the little extras that maybe your application does repetitive times throughout your code?

Well, in C#, you can use extension methods to enhance your experience.  Extension methods allow you to add functionality to existing types such as string, integers, etc.. Even sealed types are supported. They are declared as static methods and you can use them for interfaces and constructed types.

Let’s get started…

A good general practice for an extension method is to put them in their own namespaces and don’t apply them to base object classes.  This allows the developer to use them optionally if they wish.

Let’s take a quick look at how we would implement extension methods to solve our issue defined earlier in this post:  pad a string with a space on each side and multiply a number by 2 or 3.

First, lets create our string padding extension.  Take a look at the following code:

   1:  namespace App.Common.Extensions
   2:  {
   3:      public static class Strings
   4:      {
   5:          public static string PadWith(this string str, string pad)
   6:          {
   7:              return pad + str + pad;
   8:          }
   9:          public static string PadLeftWith(this string str, string pad)
  10:          {
  11:              return pad + str;
  12:          }
  13:          public static string PadRightWith(this string str, string pad)
  14:          {
  15:              return str + pad;
  16:          }
  17:      }
  18:  }

You will notice that, we have created an namespace that the developer can chose to use, along with a static class focused on Strings, that has three static string padding methods: PadWith, PadLeftWith and PadRightWith. These are just simple extension methods to pad either both, the left or the right sides of a string and return the string.

For those of you who aren’t familiar with extension methods, you will notice that the signature for the methods are static and include this string str.  This basically tells the static method what type it is going to be working with, while giving it a name to reference, str.  Then any parameters you wish to send into the method are defined.  In our case, it is string pad.

So, now, if I want to pad a string with spaces, all I need to do is the following:

   1:  public void Test()
   2:  {
   3:      var testString = "Hello";
   4:      testString = testString.PadLeftWith("Hey, ");
   5:      testString = testString.PadRightWith(" World!");
   6:      Debug.WriteLine(testString);
   7:  }

The output for this function call shows up in our output windows as follows:

image

Pretty slick huh?  How about our extension to multiply an integer by 2 or 3?  Well, here you go:

   1:  namespace App.Common.Extensions
   2:  {
   3:      public static class Integers
   4:      {
   5:          public static int MultiplyBy(this int value, int multiplier)
   6:          {
   7:              return value * multiplier;
   8:          }
   9:      }
  10:  }

Notice we allow it to be multiplied by any number, and this is how you would call it!

   1:  public void Test2()
   2:  {
   3:      var testInt = 3;
   4:      testInt = testInt.MultiplyBy(3);
   5:      Debug.WriteLine(testInt);
   6:  }

If we run our app again, this is what you would see:

Pretty simple huh?

NOTE: Now, please don’t judge me for this code.  It is just an example.  You would want to take things into consideration such as nulls, divide by zeros, exceptions, etc., but again, this is just used as an example, so you can make it as “professional” as you would like.

Hope this helped you to get ride of some of that redundant code for the mundane things you do as a coder!  If you liked this post, please share it!

 
Comments
 
Comments

Weren’t extension methods introduced in 2008?

Leave a Reply

You must be logged in to post a comment.