Wednesday, September 24, 2014

Facts about Extension Methods in C# with Practices

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:
clip_image002If the class is sealed than there in no concept of extending its functionality. To tackle with such concern we have concept of extension methods.

  2: public sealed class MathOps
  3:     {
  4:         public int Add(int x, int y)
  5:         {
  6:             return x + y;
  7:         }
  8:     }
 10: public static class StringHelper
 11:     {
 12:        public static int Add_Ex(this MathOps onjmaths, int x, int y)
 13:        {
 14:            return x + y+2;
 15:        }
 16:     }


Number2Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
Points for the 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 “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
Enjoy Coding and Readingclip_image015


Post a Comment