Thursday 9 January 2014

Extension Method in .net C#

Extension Method:

[There is no hole in my piggy bank but the money is still being inserted]
Extension Method is that kind of feature. Suppose we have a base class Employee.
This class should not be modified but I need to insert some methods in the Employee class.
No need for deriving the Employee class.
Now what is the solution?
The solution is Extension Method. Extension methods enable you to add methods to existing types without creating new derived type, recompiling or modifying the original type. Extension Methods are a special kind of static method.
Example:-
I will add the following method to String class in my program without derivation or modifying the String Class.
public static String GetFirstThreeCharacters(this String str)
        {

            if (str.Length < 3)
            {
                return str;
            }
            else
            {
                return str.Substring(0, 3);
            }
        }
Just  I have to add a static class like this .
public static class Extension
    {
        public static String GetFirstThreeCharacters(this String str)
        {

            if (str.Length < 3)
            {
                return str;
            }
            else
            {
                return str.Substring(0, 3);
            }
        }
    }

Then I can use the  GetFirstThreeCharacters in this manner in my Form Load Event.
   private void Form1_Load(object sender, EventArgs e)
        {
            String st = "My Name is Arindam";
            MessageBox.Show(st.GetFirstThreeCharacters());
        }    



No comments:

Post a Comment