Extension methods are really cool!

You can see that the arrayed variable ints has been initialized with a bunch of numbers. The extension method, OrderBy(), orders the numbers and then returns them in an IOrderedEnumerable<int>.

Now let’s make our own

Making your own extension methods is easy, but there are a few things that you first need to know. Below is a sample extension method that will convert a given string into one with alternating letter case (lower, upper, lower, upper, etc…).

Notice in the code above:

  1. The class StringExtensions is declared public static.
  2. The method AlternateCase() is declared public static.
  3. The parameter list for the method starts with the this keyword and is followed by the base type that you want to attach it to.

If you want to change the type that you’re extending then you just change the base type that follows the this keyword in the parameter list.

Alternate this!

Using the extension method is simple. All you have to do is run the method from the class.

extension_method_console

Alternate Alternate()…it’s all in the emphasis

There is another way to use your extension method, although it kinda eliminates the whole point of creating the extension method in the first place…but here it is anyways.

extension_method_console_alternate

So, that’s the gist of it. But, before you go, take care with how you use this new-found ability…

Exceptions

…especially if you’re using them in your own, soon-to-be, third-party libraries. Not every method should be an extension method. What you convert your object to or what you return from your extension method call will not always be relevant to the context of your code. Generally speaking, your extension methods should be universal to your base type.

Like I said, extension methods are really cool. There will always be a place in my heart (and code) for them.

Happy Coding!