Facts About Extension Methods in C# With Practices

This article provides some facts about Extension Methods in the C# keyword of LINQ. This keyword is very helpful when working with extensions of existing types like previously created classes.

Extension methods enable you to add methods to existing types without creating a new derived type or sub-class.

Facts: We generally previously had some helper class to extend the functionality as well as an option to create a subclass of an existing class to add new functionality.

However you may confronted with one of the following issues.

1. If the class is sealed than there is no concept of extending its functionality. To tackle such concerns we have the concept of extension methods.

concept of extension method

  1. public sealed class MathOps  
  2. {  
  3.     public int Add(int x, int y)  
  4.     {  
  5.         return x + y;  
  6.     }  
  7. }  
  8.   
  9. public static class StringHelper  
  10. {  
  11.    public static int Add_Ex(this MathOps onjmaths, int x, int y)  
  12.    {  
  13.        return x + y+2;  
  14.    }  
  15. }  
Existing type and method

2. Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.

static class

Points to remember about extension methods

 

  • An extension method must be defined in a top-level static class.
    1. public static class StringHelper  
    2. {  
    3.     public static int Add_Ex(this MathOps onjmaths, int x, int y)  
    4.     {  
    5.          return x + y + 2;  
    6.     }  
    7. }  
  • An extension method contains the “this” keyword, that must be the first parameter in the extension method parameter list.

    this keyword

  • An extension method with the same name and signature as an instance method will not be called.

    extension method with the same name and signature

  • Extension methods can't access the private/protected methods in the extended type; it prompts you an error related to protection level.

    protected at classlevel

  • The concept of extension methods cannot be applied to fields, properties or events.
These are some findings that I have shared with you.

I wish it will help you to utilize both features at best.

To learn more about MVC please go to the following link.

MVC Articles

Thanks.

Enjoy coding and reading.

Next Recommended Readings