Facts about Extension Methods in C# with Practices
In this article I am going to demonstrate some facts about Extension Methods in C# keyword of LINQ. This keyword is very helpful when working with extension of existing type like already created classes.
Extension methods enable you to add methods to existing types without creating a new derived type or sub-class.
Facts: Though we generally used to have some helper class to extend the functionality as well as have an option to create a subclass of existing class to add new functionality.
However you may confront with one of following issue as shown below:
1:2: public sealed class MathOps3: {4: public int Add(int x, int y)
5: {6: return x + y;
7: }8: }9:10: public static class StringHelper11: {12: public static int Add_Ex(this MathOps onjmaths, int x, int y)13: {14: return x + y+2;
15: }16: }17:
Points for the Remember about extension methods
· An extension method must be defined in a top-level static class
1: public static class StringHelper2: {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 “this” keyword, which has to 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 all are some finding which I have shared with you.
I wish it will help you utilize both feature at best.
To learn more about MVC please go to the following link.
MVC Articles
Thanks
Enjoy Coding and Reading
0 comments :
Post a Comment