As we have already mentioned in the previous chapter, we are going to discuss extension methods in greater detail in this chapter. It will be helpful when we talk about LINQ, the essential technique of functional programming in C#, in the next chapter. The following are the topics we will cover in this chapter:
An extension method is a capability that can extend the ability of an existing class or type without making any modification to the existing class or type. This means that an extension method enables us to add methods to the existing class or type without having to either create a new derived type or recompile.
Extension methods were introduced in C# 3.0 and can be applied to our own types or existing types in .NET. The extension method will be used a lot in functional programming since it suits the method chaining concept, which we have already used in Chapter 1, Tasting Functional Style in C#, when refactoring code in a functional style.
Extension methods have to be declared in a static, nongeneric, and non-nested class. They are a static method inside a static class. To create an extension method, first we have to create a public static
class since the extension methods have to be included in the static
class. After the public static
class is successfully created, we define a method inside the class and add the this
keyword to the first method argument to indicate that it is an extension
method. The first argument in the method that has the this
keyword has to refer to a specific instance of the class we want to extend. In order to make the explanation clearer, let's take a look at the following code, creating a extension method that we can find in the Palindrome.csproj
project:
public static class ExtensionMethods { public static bool IsPalindrome(this string str) { char[] array = str.ToCharArray(); Array.Reverse(array); string backwards = new string(array); return str == backwards; } }
Now let's dissect the preceding code to understand how the extension method is created. First, we have to successfully create the public static
class, as shown in the following code snippet:
public static class ExtensionMethods { ... }
Then, we create a static
method inside the class, as shown in the following code snippet:
public static bool IsPalindrome(this string str) { ... }
As we can see in the preceding method, we add the this
keyword in the first argument of the method. This indicates that the method is an extension
method. Also, the type of the first argument, which is string, indicates that the type we want to extend is the string
data type. Now, by defining the IsPalindrome()
extension method for the string
type, all instances of string have the IsPalindrome()
method. Let's take a look at the following code to prove this:
public class Program { static void Main(string[] args) { string[] strArray = { "room", "level", "channel", "heat", "burn", "madam", "machine", "jump", "radar", "brain" }; foreach (string s instrArray) { Console.WriteLine("{0} = {1}", s, s.IsPalindrome()); } } }
The preceding Main()
function will examine all members of the strArray
array, whether or not it is palindrome. We can call the IsPalindrome()
method from the s
variable in which it's a string
type variable. The code snippet when the IsPalindrome()
method is invoked from an instance of the string type is as follows:
foreach (string s instrArray) { Console.WriteLine("{0} = {1}", s, s.IsPalindrome()); }
If we run the Palindrome.csproj
project, we can get the following output on the console:
Since the palindrome is a word or another sequence of characters that will be the same whether we read backward or forward, only level
, madam
, and radar
will return true
if we invoke the IsPalindrome()
method to them. Our extension method has been successfully created and run.
When we create an extension method for instance, to a type there will be no apparent difference compared to the existing methods in a class or type. This is because we will do the same thing when invoking extension methods or methods that are actually defined in a type. However, we can inspect the code IntelliSense to understand whether or not the method inside the type is an extension method since the extension method will be displayed in the IntelliSense. The following screenshot is the method list for the string instance when the IsPalindrome()
extension method has not been defined yet:
And the following screenshot is the method list for the string instance when the IsPalindrome()
extension method has been defined:
We can see from the preceding two images that the extension will be listed in the code IntelliSense of Visual Studio. However, we can now find the distinction between extension methods and methods that are actually defined in a type that is the icon. There is an arrow pointing down at the icon of extension methods although we cannot find it in the method that is actually defined in a type. This is because the icon is different but the way we invoke the method is totally the same.