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.
- public sealed class MathOps
- {
- public int Add(int x, int y)
- {
- return x + y;
- }
- }
-
- public static class StringHelper
- {
- public static int Add_Ex(this MathOps onjmaths, int x, int y)
- {
- return x + y+2;
- }
- }
2. Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
Points to remember about extension methods
- An extension method must be defined in a top-level static class.
- public static class StringHelper
- {
- public static int Add_Ex(this MathOps onjmaths, int x, int y)
- {
- return x + y + 2;
- }
- }
- An extension method contains the “this” keyword, that must be the first parameter in the extension method parameter list.
- An extension method with the same name and signature as an instance method will not be called.
- Extension methods can't access the private/protected methods in the extended type; it prompts you an error related to protection level.
- 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 ArticlesThanks.
Enjoy coding and reading.