Extension methods are really cool!
1 2 3 4 5 6 7 8 9 10 |
class ExtensionMethods{ static void Main(){ int[] ints = { 10, 45, 15, 39, 21, 26 }; var result = ints.OrderBy(g => g); foreach (var i in result){ System.Console.Write(i + " "); } } } //Output: 10 15 21 26 39 45 |
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…).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
namespace ExtensionMethods { public static class StringExtensions { public static string AlternateCase(this string original) { string result = string.Empty; char[] chars = original.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if (i % 2 == 0) { result += chars[i].ToString().ToLower(); } else { result += chars[i].ToString().ToUpper(); } } return result; } } } |
Notice in the code above:
- The class
StringExtensions
is declaredpublic static
. - The method
AlternateCase()
is declaredpublic static
. - 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.
1 2 3 4 5 6 |
class Program { static void Main(string[] args) { string result = "Alternating Case".AlternateCase(); Console.Write(result); } } |
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.
1 2 3 4 5 6 |
class Program { static void Main(string[] args) { string result = ExtensionMethods.StringExtensions.AlternateCase("This works too"); Console.Write(result); } } |
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.