Extension methods are a powerful way of gluing your own custom functionality onto types you don't own, and make them accessible like static instance methods to the type, instead of creating a wrapper around the type.
The basics
As a very simple example, we might want to have a method on the the simple int type, that evaluates whether the value is an even number.
So we simply create a static method in a static class, and use the C# extension method shortcut this in the method signature, indicating that the compiler needs to perform a little magic for us with the int type, and implement the IsEven check.
namespace Extensions { public static class Extensions { public static bool IsEven(this int number) { return number % 2 == 0; } } }
Now we can check whether the int is even or uneven with our extension method, here in a test method:
[TestMethod] public void IsEvenTest() { int even = 2; int uneven = 3; Assert.IsTrue(even.IsEven()); Assert.IsFalse(uneven.IsEven()); }
Notice that the method is marked as an extension method in our intellisense with both an icon with an arrow down and with the (extension) tag, to avoid confusion:
So what you need to create an extension method is:
Pretty simple and powerful. In my next post I will look at how this actually works.
Remember Me