Wednesday, September 24, 2014

Facts about Extension Methods in C# with Practices

Facts about Extension Methods in C# with Practices

Dotnetpiper

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.
 
clip_image003
 

  1: 
  2: public sealed class MathOps
  3:     {
  4:         public int Add(int x, int y)
  5:         {
  6:             return x + y;
  7:         }
  8:     }
  9: 
 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:     }
 17: 




clip_image006

 
Number2Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
clip_image008
 
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.



clip_image010

 

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



clip_image012

 

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

 
clip_image014


  • 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 Readingclip_image015





















0 comments :

Post a Comment