Extension Method In C#

I believe that many of you will define some static functions and put them to a static class. This class we usually called a util class. Just like the following code snippet. I define a class called EnumerableUtil and define a “HeadThree” function. 

This function can get top 3 elements.

Then. We invoke this function and get the expected result. 

This style usually appears before net framework 3.5 before. But after .net 3.5, Microsoft provides a flexible programming style call extension method. This style makes your code structure to be more like object oriented style.

Let’s look at the following instance, we define the same function “HeadThree”. But this time, we put this function in an EnumerableExtension file. 

Once you try to invoke this function in your program, you don’t need the invoke other class to invoke this function. You can invoke it directly by “IEnumerable” class like the above example.

Why C# can find this function from “IEnumerable” class? It’s because the latest .net framework find the called function from current class. Once there is no definition of this function inside this class. The compiler will further find this function through your import namespace. Because “ExtensionMethodExample” namespace contains a class called Enumerable Extensions and have the called function definition. So there is no compile error. 

The other advantage of Extension Method is that it makes your code more cosine. For instance, if you want to calculate the head 3 difference of “IEnumerable<int>”, In util programming style, you define a difference function and then call it step by step.


But, if your adopt the extension style, the code will be something like that

The process of take the head three difference are computed by the one line code. "data.headThree<int>()>difference();"

 It is shorter than util programming style. The code will be more readable.

Best practice. 

There are 5 point you should noticed.

  1. The method must be static and it is not a generic static class. 
  2. At least has one parameter.
  3. The first parameter must be “this parameter”
  4. The first parameter cannot is “out” or “ref” parameter.

Finally, although the static method will become an extension method once you put “this” keyword in the first parameter. But it still can be invoked like static class method style. For instance,   

IEnumerable<int> subdata3 = EnumerableExtension.headThree<int>(data); 

The above code can be run successfully. The source code of this article I post it on my github https://github.com/Isaac234517/C-_ExtensionMethodExample

Thank you!


Get the latest article from lab.

Please leave your email below.

Subscribe

Thank you for you subscription